Python - Accessing every 1st element of Pandas DataFrame column containing lists

Given a Pandas DataFrame, we have to access every 1st element of its column containing lists. By Pranit Sharma Last updated : September 29, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

A list is a collection of the heterogeneous type of elements which means the data inside a list can be of any type. A list in python is just like an array where the first element has an index of 1 and the last element has an index n-1 where n is the length of the list.

Problem statement

Suppose, we have a DataFrame with a column 'A' which contains a list of multiple values at some rows and normal values at some other rows. We will access the first element of every value if the value is in the form of a list.

Accessing every 1st element of Pandas DataFrame column containing lists

For this purpose, you the .str[0] with the DataFrame's column name (df["A"]) and assign the result as a new column in the existing DataFrame. Consider the below-given code statement,

df['New'] = df["A"].str[0]

Let us understand how to access the first element of the column if the column is the list,

Python program to access every 1st element of Pandas DataFrame column containing lists

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {'A':[[1,2,3],[7,8,9],['a','b','c'],['g','h','i']]}

# Creating DataFrame
df=pd.DataFrame(d)

# Display the DataFrame
print("Original DataFrame:\n",df,"\n\n")

# making new column
df['New'] = df["A"].str[0]

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example: Accessing every 1st element of column containing lists

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.