Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

How to Access a list within an element of a Pandas DataFrame

To access a list within an element of a Pandas DataFrame, you can use the .loc[] or .iloc[] indexing methods. Here’s an example:

Suppose we have the following DataFrame:

import pandas as pd

df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Charlie'],
    'grades': [[90, 80, 95], [85, 75, 70], [95, 90, 100]]
})

The grades column contains lists of grades for each student. To access the first grade of the second student (Bob), you can use .loc[] or .iloc[] as follows:

# Using .loc[]
print(df.loc[1, 'grades'][0])  # Output: 85

# Using .iloc[]
print(df.iloc[1, 1][0])  # Output: 85

In both cases, we specify the row and column indexes of the element we want to access, and then use indexing to access the first element of the list. Note that in this example, we use the integer index 1 to refer to the second row and column, because the DataFrame does not have a default index. If your DataFrame has a default index, you can use it instead of the integer index.

Verified by MonsterInsights