Get list from pandas dataframe column or row?
In Pandas, a DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can access a column of a DataFrame as a Series object by using the column's name as an attribute. For example:
import pandas as pd
# Create a simple DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
# Access the column 'A' as a Series
column_a = df['A']
# Access the column 'A' as a list
column_a_list = df['A'].tolist()
Watch a video course
Python - The Practical Guide
If you would like to access a row of DataFrame as a Series, you can use the loc
accessor to select a row by its label and returns a Series, the iloc
accessor to select a row by its integer position in the DataFrame and returns a Series.
# Access the first row as a Series
first_row = df.loc[0] # or df.iloc[0]
# Access the first row as a list
first_row_list = df.loc[0].tolist() # or df.iloc[0].tolist()
Note that the index in a DataFrame is also a column, so if you have an index in your DataFrame, like a timestamp, you can also use it to slice or select rows and columns, like:
# dataframe with timestamp as index
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},index=pd.date_range('2022-01-01',periods=3))
df.loc['2022-01-01','A']
You can also filter the rows using the logical operations,
df[df.A>1]
and select specific columns after that as well
df[df.A>1]['B']