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

  1. The code begins by importing the pandas library.
  2. It then creates a DataFrame object from a dictionary. The DataFrame contains two columns, 'fruit' and 'price'.
  3. The code then calls the 'tolist()' method on the 'price' column. This returns a list of all the values in the 'price' column.
  4. 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

  1. The first line creates a DataFrame called df with two columns, fruit_name, and price.
  2. The second line creates a list called result which contains the values from the fruit_name column in the df DataFrame.
  3. The third line prints the list called result.
Was this helpful?