python
Get column values as list in Pandas DataFrame
If you have a Pandas DataFrame and want to get a list of the values in a column, it is easy to do by using the column name as an index. For example, given a DataFrame with a column "column_name", you can get a list of the values in that column like this: df['column_name'].tolist()
import pandas as pd
# create a datatframe
df = pd.DataFrame({
'fruit': ['Banana', 'Apple', 'Mango', 'Orange', 'Papaya'],
'price': [50, 60, 90, 70, 30]
})
print(df)
# get all values from a column as a list
result = df['price'].tolist()
print(result)
Output
+----+---------+---------+
| | fruit | price |
|----+---------+---------|
| 0 | Banana | 50 |
| 1 | Apple | 60 |
| 2 | Mango | 90 |
| 3 | Orange | 70 |
| 4 | Papaya | 30 |
+----+---------+---------+
[50, 60, 90, 70, 30]
Walkthrough
- The code begins by importing the pandas library.
- It then creates a DataFrame object from a dictionary. The DataFrame contains two columns, 'fruit' and 'price'.
- The code then calls the 'tolist()' method on the 'price' column. This returns a list of all the values in the 'price' column.
- Finally, the code prints the list to the console.
Syntax
df['column_name'].tolist()
If you want to get all values in the fruit column, you can use the below code.
df['fruit'].tolist()
Output
['Banana', 'Apple', 'Mango', 'Orange', 'Papaya']
Get column values as list using list() function
In Python, the list() function allows you to convert a column of data into a list. This is useful if you want to perform an operation on all of the values in a column. We will use this function to get all the values in the DataFrame column.
Syntax
list(df['column_name'])
Code example
df = pd.DataFrame({
'fruit_name': ['Banana', 'Apple', 'Mango', 'Orange', 'Papaya'],
'price': [50, 60, 90, 70, 30]
})
result = list(df['fruit_name'])
print(result)
Output
['Banana', 'Apple', 'Mango', 'Orange', 'Papaya']
In the above code example
- The first line creates a DataFrame called df with two columns, fruit_name, and price.
- The second line creates a list called result which contains the values from the fruit_name column in the df DataFrame.
- The third line prints the list called result.
Was this helpful?
Similar Posts
- Change column orders using column names list - Pandas Dataframe
- [Pandas] Add new column to DataFrame based on existing column
- Get column names from Pandas DataFrame as a python List
- Get a column rows as a List in Pandas Dataframe
- Pandas - Delete,Remove,Drop, column from pandas DataFrame
- Check if a column contains zero values only in Pandas DataFrame
- Change column values condition based in Pandas DataFrame