Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a list within an element of a Pandas DataFrame

I have a Pandas DataFrame which has a list of integers inside one of the columns. I'd like to access the individual elements within this list. I've found a way to do it by using tolist() and turning it back into a DataFrame, but I am wondering if there is a simpler/better way. In this example, I add Column A to the middle element of the list in Column B.

import pandas as pd
df = pd.DataFrame({'A' : (1,2,3), 'B': ([0,1,2],[3,4,5,],[6,7,8])})
df['C'] = df['A'] + pd.DataFrame(df['B'].tolist())[1]
df

Is there a better way to do this?

like image 307
Michael Avatar asked Jun 29 '16 00:06

Michael


People also ask

How do I get a list from a DataFrame column?

tolist() you can convert pandas DataFrame Column to List. df['Courses'] returns the DataFrame column as a Series and then use values. tolist() to convert the column values to list.

How do you access a specific element in a DataFrame?

By using at and iat attributes We can also access a single value of a DataFrame with the help of “at” and “iat” attributes. Access a single value by row/column name. At and iat take two arguments. If we pass only one argument, then it will generate an error.

Can pandas DataFrame hold list?

By using df.at() , df. iat() , df. loc[] method you can insert a list of values into a pandas DataFrame cell.

Can a list be an element of a DataFrame?

The pandas DataFrame can be created by using the list of lists, to do this we need to pass a python list of lists as a parameter to the pandas. DataFrame() function. Pandas DataFrame will represent the data in a tabular format, like rows and columns.


1 Answers

A bit more straightforward is:

df['C'] = df['A'] + df['B'].apply(lambda x:x[1])
like image 70
breucopter Avatar answered Nov 14 '22 23:11

breucopter