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?
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.
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.
By using df.at() , df. iat() , df. loc[] method you can insert a list of values into a pandas DataFrame cell.
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.
A bit more straightforward is:
df['C'] = df['A'] + df['B'].apply(lambda x:x[1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With