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
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']
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
0 Comments