- Pandas DataFrame to a List in Python
- How to covert a pandas dataframe to a list?
- Examples
- 1. List with DataFrame rows as items
- 2. List with DataFrame columns as items
- 3. List from a DataFrame by iterating through the rows
- Author
- How to Convert Pandas DataFrame Row to List (With Example)
- Example: Convert Pandas DataFrame Row to List
- Additional Resources
- How to Convert Pandas Column or Row to List
- Setup
- Convert column to list
- Convert row to list
- Convert column with list values to row
- Column from lists (string) to lists
- How to write Python / Pandas rows and columns into a list?
- Creating your sample Dataframe
- Convert a column/series to list of strings
- Convert a Pandas row to a list
- Convert a dataframe to a list of lists
- Convert a Pandas Series to a list
Pandas DataFrame to a List in Python
Pandas dataframes are great for manipulating data. But, at times it might happen that you’d rather have the data as a list (or more precisely, a list of lists). In this tutorial, we’ll look at how to convert a pandas dataframe to a python list.
How to covert a pandas dataframe to a list?
There are multiple ways to get a python list from a pandas dataframe depending upon what sort of list you want to create. To quickly get a list from a dataframe with each item representing a row in the dataframe, you can use the tolist() function like df.values.tolist()
📚 Discover Online Data Science Courses & Programs (Enroll for Free)
Introductory ⭐
Intermediate ⭐⭐⭐
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
However, there are other ways as well. You can create a list with each item representing a dataframe column. Or, you can create something very specific based on your requirements. Let’s look at some of the different use cases with examples.
Examples
First, let’s create a dataframe of a sample stock portfolio that we’ll be using throughout this tutorial.
import pandas as pd data = < 'Name': ['Microsoft Corporation', 'Google, LLC', 'Tesla, Inc.',\ 'Apple Inc.', 'Netflix, Inc.'], 'Symbol': ['MSFT', 'GOOG', 'TSLA', 'AAPL', 'NFLX'], 'Industry': ['Tech', 'Tech', 'Automotive', 'Tech', 'Entertainment'], 'Shares': [100, 50, 150, 200, 80] >df = pd.DataFrame(data) print(df)
Name Symbol Industry Shares 0 Microsoft Corporation MSFT Tech 100 1 Google, LLC GOOG Tech 50 2 Tesla, Inc. TSLA Automotive 150 3 Apple Inc. AAPL Tech 200 4 Netflix, Inc. NFLX Entertainment 80
The following are some of the ways to get a list from a pandas dataframe explained with examples.
1. List with DataFrame rows as items
As mentioned above, you can quickly get a list from a dataframe using the tolist() function.
ls = df.values.tolist() print(ls)
[['Microsoft Corporation', 'MSFT', 'Tech', 100], ['Google, LLC', 'GOOG', 'Tech', 50], ['Tesla, Inc.', 'TSLA', 'Automotive', 150], ['Apple Inc.', 'AAPL', 'Tech', 200], ['Netflix, Inc.', 'NFLX', 'Entertainment', 80]]
In the above example, df.values returns the numpy representation of the dataframe df which is then converted to a list using the tolist() function. You can see that we get a list of lists with each item in the list representing a row in the dataframe.
2. List with DataFrame columns as items
You can also use tolist() function on individual columns of a dataframe to get a list with column values.
# list with each item representing a column ls = [] for col in df.columns: # convert pandas series to list col_ls = df[col].tolist() # append column list to ls ls.append(col_ls) # print the created list print(ls)
[['Microsoft Corporation', 'Google, LLC', 'Tesla, Inc.', 'Apple Inc.', 'Netflix, Inc.'], ['MSFT', 'GOOG', 'TSLA', 'AAPL', 'NFLX'], ['Tech', 'Tech', 'Automotive', 'Tech', 'Entertainment'], [100, 50, 150, 200, 80]]
In the above example, we iterate through each column of the dataframe which is converted to a list and then appended to ls . You can see that here we get a list of lists with each item in the list representing a column in the dataframe.
3. List from a DataFrame by iterating through the rows
You can also create a list by iterating through the rows of the dataframe.
ls = [] # iterate over the rows for i, row in df.iterrows(): # create a list representing the dataframe row row_ls = [row['Name'], row['Symbol'], row['Industry'], row['Shares']] # append row list to ls ls.append(row_ls) print(ls)
[['Microsoft Corporation', 'MSFT', 'Tech', 100], ['Google, LLC', 'GOOG', 'Tech', 50], ['Tesla, Inc.', 'TSLA', 'Automotive', 150], ['Apple Inc.', 'AAPL', 'Tech', 200], ['Netflix, Inc.', 'NFLX', 'Entertainment', 80]]
In the above example, we use the pandas dataframe iterrows() function to iterate over the rows of df and create a list with row values which gets appended to ls . You can see that we get a list of lists with each item in the list representing a row in the dataframe like we saw in the example with the tolist() function.
This method also allows you the flexibility to create specific lists based on your requirements. For instance, from the above dataframe if you want to create a list of lists with only the stock symbol and its respective share count you can easily do it by keeping only those fields.
ls = [] # iterate over the rows for i, row in df.iterrows(): # create a list representing the dataframe row row_ls = [row['Symbol'], row['Shares']] # append row list to ls ls.append(row_ls) print(ls)
[['MSFT', 100], ['GOOG', 50], ['TSLA', 150], ['AAPL', 200], ['NFLX', 80]]
Here, we get a list of lists with each item having the stock symbol and the respective shares count in the portfolio.
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having pandas version 1.0.5
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
- Pandas – Sort a DataFrame
- Change Order of Columns of a Pandas DataFrame
- Pandas DataFrame to a List in Python
- Pandas – Count of Unique Values in Each Column
- Pandas – Replace Values in a DataFrame
- Pandas – Filter DataFrame for multiple conditions
- Pandas – Random Sample of Rows
- Pandas – Random Sample of Columns
- Save Pandas DataFrame to a CSV file
- Pandas – Save DataFrame to an Excel file
- Create a Pandas DataFrame from Dictionary
- Convert Pandas DataFrame to a Dictionary
- Drop Duplicates from a Pandas DataFrame
- Concat DataFrames in Pandas
- Append Rows to a Pandas DataFrame
- Compare Two DataFrames for Equality in Pandas
- Get Column Names as List in Pandas DataFrame
- Select One or More Columns in Pandas
- Pandas – Rename Column Names
- Pandas – Drop one or more Columns from a Dataframe
- Pandas – Iterate over Rows of a Dataframe
- How to Reset Index of a Pandas DataFrame?
- Read CSV files using Pandas – With Examples
- Apply a Function to a Pandas DataFrame
Author
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts
Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.
How to Convert Pandas DataFrame Row to List (With Example)
You can use the following basic syntax to convert a row in a pandas DataFrame to a list:
row_list = df.loc[2, :].values.flatten().tolist()
This particular syntax converts the values in row index position 2 of the DataFrame into a list.
The following example shows how to use this syntax in practice.
Example: Convert Pandas DataFrame Row to List
Suppose we have the following pandas DataFrame that contains information about various basketball players:
import pandas as pd #create DataFrame df = pd.DataFrame(team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], 'points': [18, 22, 19, 14, 14, 11, 20, 28], 'assists': [5, 7, 7, 9, 12, 9, 9, 4], 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]>) #view DataFrame print(df) team points assists rebounds 0 A 18 5 11 1 B 22 7 8 2 C 19 7 10 3 D 14 9 6 4 E 14 12 6 5 F 11 9 5 6 G 20 9 9 7 H 28 4 12
We can use the following syntax to convert the values in row index position 2 to a list:
#convert row at index 2 to list row_list = df.loc[2, :].values.flatten().tolist() #view results print(row_list) ['C', 19, 7, 10]
We can see that the values in row index position 2 have been converted to a list with four values.
We can confirm that the result is indeed a list by using the type() function:
#view type print(type(row_list))
If you only want the values from specific columns to be included in the list, you can specify the columns by name.
For example, we can use the following syntax to convert the values in row index position 2 to a list for the team and points columns only:
#convert values in row index position 2 to list (for team and points columns) row_list = df.loc[2, ['team', 'points']].values.flatten().tolist() #view results print(row_list) ['C', 19]
Notice that only the values in the team and points columns have been included in the list.
Additional Resources
The following tutorials explain how to perform other common tasks in pandas:
How to Convert Pandas Column or Row to List
To convert a DataFrame column or row to a list in Pandas, we can use the Series method tolist() . Here’s how to do it:
Image below shows some of the solutions described in this article:
Setup
We will use the following DataFrame to convert rows and columns to list:
```python import pandas as pd df = pd.DataFrame()
A | B | |
---|---|---|
0 | 1 | 4 |
1 | 2 | 5 |
2 | 3 | 6 |
Convert column to list
To convert a column to a list, we can access the column using either
and then call the tolist() method on the resulting pandas Series object:
Convert row to list
To get a list from a row in a Pandas DataFrame, we can use the iloc indexer to access the row by its index. Then call the tolist() method on the resulting pandas Series object:
Convert column with list values to row
We can convert columns which have list values to rows by using method .explode() . The example below shows how to convert column B which has list values. We will use new DataFrame:
A | B | |
---|---|---|
0 | a | [1, 2] |
1 | b | [3, 4, 5] |
Column from lists (string) to lists
Finally let’s check how to convert column which contains list values stored as strings to list:
import pandas as pd data_dict = df = pd.DataFrame(data_dict)
one | two | |
---|---|---|
a | 1 | [1, 2] |
b | 2 | [3, 4] |
c | 3 | [5, 6] |
We can extract list values by using list comprehensions:
[x.strip('[]').split(',') for x in df['two']]
which result into new list of lists:
If we like to keep the list values in the column we can use ast module:
import ast df.two.apply(ast.literal_eval)
a [1, 2] b [3, 4] c [5, 6] Name: two, dtype: object
By using DataScientYst — Data Science Simplified, you agree to our Cookie Policy.
How to write Python / Pandas rows and columns into a list?
There are cases in which when working with Pandas Dataframes and data series objects you might need to convert those into lists for further processing.
In this post we’ll convert into lists (or list of lists) the following:
- Dataframe columns
- Dataframe rows
- Entire Dataframes
- Data series arrays
Creating your sample Dataframe
Before we get started let’s set the environment and create a simple Dataframe to work with. We’ll convert a Python dictionary containing fictitious information on programming languages and their perceived popularity. This is just for training/learning purposes, as in real live you’ll be importing your data from .csv files (read_csv), JSON, sql databases and so forth.
Paste the following into your favorite Python editor to create the test Dataframe.
# Python3 import pandas as pd data = pd.DataFrame()
Let’s take a look at the data. Run the following:
Convert a column/series to list of strings
Let’s go ahead and convert the Language column to a list of strings. Here’s how you can easily do it:
languages = list(data["Language"])
Python created a list of strings:
[‘Ruby’, ‘PHP’, ‘JavaScript’, ‘C-Sharp’, ‘VB.NET’, ‘Python’]Convert a Pandas row to a list
Now we would like to extract one of the dataframe rows into a list. For simplicity let’s just take the first row of our Pandas table.
#Python3 first_row = list(data.loc[0])
Let’s look into the result:
Python created a list containing the first row values:
Convert a dataframe to a list of lists
We just learnt that we are able to easily convert rows and columns to lists. But what if we want to convert the entire dataframe?
We’ll return the following list of lists:
[['Ruby', 400], ['PHP', 100], ['JavaScript', 500], ['C-Sharp', 300], ['VB.NET', 200], ['Python', 1000]]
Convert a Pandas Series to a list
We’ll first going to quickly create a data Series from a Numpy array Then export it back to a list. Here we go:
#Python3 import numpy as np ds = pd.Series(np.array([1,2,3,4,5]) list(ds)
And the output will be a list:
That’ it for today, happy data wrangling 🙂