- Pandas: Convert a dataframe column into a list using Series.to_list() or numpy.ndarray.tolist() in python
- Frequently Asked:
- Convert a Dataframe column into a list using Series.to_list()
- How did it work?
- Convert a Dataframe column into a list using numpy.ndarray.tolist()
- How did it work?
- Related posts:
- Convert pandas Series to List in Python
- Using list() to Convert pandas Series to List in Python
- Other Articles You’ll Also Like:
- About The Programming Expert
Pandas: Convert a dataframe column into a list using Series.to_list() or numpy.ndarray.tolist() in python
In this article, we will discuss different ways to convert a dataframe column into a list.
Fits of all, create a dataframe object that we are going to use in this example,
import pandas as pd # List of Tuples students = [('jack', 34, 'Sydney', 155), ('Riti', 31, 'Delhi', 177.5), ('Aadi', 16, 'Mumbai', 81), ('Mohit', 31, 'Delhi', 167), ('Veena', 12, 'Delhi', 144), ('Shaunak', 35, 'Mumbai', 135), ('Shaun', 35, 'Colombo', 111) ] # Create a DataFrame object student_df = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score']) print(student_df)
Name Age City Score 0 jack 34 Sydney 155.0 1 Riti 31 Delhi 177.5 2 Aadi 16 Mumbai 81.0 3 Mohit 31 Delhi 167.0 4 Veena 12 Delhi 144.0 5 Shaunak 35 Mumbai 135.0 6 Shaun 35 Colombo 111.0
Now how to fetch a single column out of this dataframe and convert it to a python list?
Frequently Asked:
There are different ways to do that, lets discuss them one by one.
Convert a Dataframe column into a list using Series.to_list()
To turn the column ‘Name’ from the dataframe object student_df to a list in a single line,
# select a column as series and then convert it into a column list_of_names = student_df['Name'].to_list() print('List of Names: ', list_of_names) print('Type of listOfNames: ', type(list_of_names))
List of Names: [‘jack’, ‘Riti’, ‘Aadi’, ‘Mohit’, ‘Veena’, ‘Shaunak’, ‘Shaun’] Type of listOfNames:
How did it work?
Let’s break down the above line into steps,
Step 1: Fetch a column as series
Select the column ‘Name’ from the dataframe using [] operator,
# Select column 'Name' as series object names = student_df['Name'] print(names) print(type(names))
0 jack 1 Riti 2 Aadi 3 Mohit 4 Veena 5 Shaunak 6 Shaun Name: Name, dtype: object
It returns a Series object names, and we have confirmed that by printing its type.
Step 2 : Convert the Series object to the list
Series class provides a function Series.to_list(), which returns the contents of Series object as list. Use that to convert series names into a list i.e.
# Convert series object to a list list_of_names = names.to_list() print('List of Names: ', list_of_names) print('Type of listOfNames: ', type(list_of_names))
List of Names: [‘jack’, ‘Riti’, ‘Aadi’, ‘Mohit’, ‘Veena’, ‘Shaunak’, ‘Shaun’] Type of listOfNames:
This is how we converted a dataframe column into a list.
Important Note:
It might be possible that it gives you an error i.e.
AttributeError: 'Series' object has no attribute 'to_list'
If you get that error, then please check your Pandas version, you may be using pandas version less than 24.
Import pandas as pd print(pd.__version__)
Upgrade you pandas to the latest version using the following command,
pip install --upgrade pandas
Convert a Dataframe column into a list using numpy.ndarray.tolist()
Another way is converting a Dataframe column into a list is,
# Convert column Name to a Numpy Array and then to a list list_of_names = student_df['Name'].values.tolist() print('List of Names: ', list_of_names) print('Type of listOfNames: ', type(list_of_names))
List of Names: [‘jack’, ‘Riti’, ‘Aadi’, ‘Mohit’, ‘Veena’, ‘Shaunak’, ‘Shaun’] Type of listOfNames:
We converted the column ‘Name’ into a list in a single line. Let’s see what happened inside it,
How did it work?
Let’s break down the above line into steps,
Step 1: Select a column as a Series object
Select the column ‘Name’ from the dataframe using [] operator,
It returns a Series object.
Step 2: Get a Numpy array from a series object using Series.Values
# Select a column from dataframe as series and get a numpy array from that names = student_df['Name'].values print('Numpy array: ', names) print('Type of namesAsNumpy: ', type(names))
Numpy array: [‘jack’ ‘Riti’ ‘Aadi’ ‘Mohit’ ‘Veena’ ‘Shaunak’ ‘Shaun’] Type of namesAsNumpy:
Names is a numpy array, and we confirmed it by printing its types.
Step 3: Convert a Numpy array into a list
Numpy array provides a function tolist() to convert its contents to a list,
# Convert numpy array to a list list_of_names = names.tolist() print('List of Names: ', list_of_names) print('Type of listOfNames: ', type(list_of_names))
List of Names: [‘jack’, ‘Riti’, ‘Aadi’, ‘Mohit’, ‘Veena’, ‘Shaunak’, ‘Shaun’] Type of listOfNames:
This is how we selected our column ‘Name’ from Dataframe as a Numpy array and then turned it to a list.
The complete example is as follows,
import pandas as pd def main(): # List of Tuples students = [('jack', 34, 'Sydney', 155), ('Riti', 31, 'Delhi', 177.5), ('Aadi', 16, 'Mumbai', 81), ('Mohit', 31, 'Delhi', 167), ('Veena', 12, 'Delhi', 144), ('Shaunak', 35, 'Mumbai', 135), ('Shaun', 35, 'Colombo', 111) ] # Create a DataFrame object student_df = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score']) print("Contents of the Dataframe : ") print(student_df) print('Convert a Dataframe column into a list using Series.to_list()') # select a column as series and then convert it into a column list_of_names = student_df['Name'].to_list() print('List of Names: ', list_of_names) print('Type of listOfNames: ', type(list_of_names)) print('How did it worked ?') # Select column 'Name' as series object names = student_df['Name'] print(names) print(type(names)) # Convert series object to a list list_of_names = names.to_list() print('List of Names: ', list_of_names) print('Type of listOfNames: ', type(list_of_names)) print("Convert a Dataframe column into a list using numpy.ndarray.tolist()") # Convert column Name to a Numpy Array and then to a list list_of_names = student_df['Name'].values.tolist() print('List of Names: ', list_of_names) print('Type of listOfNames: ', type(list_of_names)) print('How did it worked ?') # Select a column from dataframe as series and get a numpy array from that names = student_df['Name'].values print('Numpy array: ', names) print('Type of namesAsNumpy: ', type(names)) # Convert numpy array to a list list_of_names = names.tolist() print('List of Names: ', list_of_names) print('Type of listOfNames: ', type(list_of_names)) if __name__ == '__main__': main()
Contents of the Dataframe : Name Age City Score 0 jack 34 Sydney 155.0 1 Riti 31 Delhi 177.5 2 Aadi 16 Mumbai 81.0 3 Mohit 31 Delhi 167.0 4 Veena 12 Delhi 144.0 5 Shaunak 35 Mumbai 135.0 6 Shaun 35 Colombo 111.0 Convert a Dataframe column into a list using Series.to_list() List of Names: [‘jack’, ‘Riti’, ‘Aadi’, ‘Mohit’, ‘Veena’, ‘Shaunak’, ‘Shaun’] Type of listOfNames: How did it worked ? 0 jack 1 Riti 2 Aadi 3 Mohit 4 Veena 5 Shaunak 6 Shaun Name: Name, dtype: object List of Names: [‘jack’, ‘Riti’, ‘Aadi’, ‘Mohit’, ‘Veena’, ‘Shaunak’, ‘Shaun’] Type of listOfNames: Convert a Dataframe column into a list using numpy.ndarray.tolist() List of Names: [‘jack’, ‘Riti’, ‘Aadi’, ‘Mohit’, ‘Veena’, ‘Shaunak’, ‘Shaun’] Type of listOfNames: How did it worked ? Numpy array: [‘jack’ ‘Riti’ ‘Aadi’ ‘Mohit’ ‘Veena’ ‘Shaunak’ ‘Shaun’] Type of namesAsNumpy: List of Names: [‘jack’, ‘Riti’, ‘Aadi’, ‘Mohit’, ‘Veena’, ‘Shaunak’, ‘Shaun’] Type of listOfNames:
Related posts:
Convert pandas Series to List in Python
To convert a pandas Series to a list in Python, the easiest way by using values.tolist() on a pandas Series.
import pandas as pd df = pd.DataFrame() animal_types = df["animal_type"].values.tolist() print(animal_types) #Output: ['dog', 'cat', 'dog', 'cat', 'dog', 'dog', 'cat', 'cat', 'dog']
You can also use list() function to convert a pandas Series to a list.
import pandas as pd df = pd.DataFrame() animal_types = list(df["animal_type"]) print(animal_types) #Output: ['dog', 'cat', 'dog', 'cat', 'dog', 'dog', 'cat', 'cat', 'dog']
When working with collections of data, the ability to be able to easily access certain pieces of information is valuable.
One such situation is if you want to get the values of a pandas Series and create a list in Python.
There are a few ways you can convert the values of a pandas Series to a list.
Having values of a Series in a list can be useful if you want to loop over the values and perform an action.
The easiest way is to access the Series values with the pandas Series values attribute and then use the tolist() function.
Below shows a simple example of how you can convert a pandas Series to list in Python.
import pandas as pd df = pd.DataFrame() animal_types = df["animal_type"].values.tolist() print(animal_types) #Output: ['dog', 'cat', 'dog', 'cat', 'dog', 'dog', 'cat', 'cat', 'dog']
Using list() to Convert pandas Series to List in Python
Another way you can convert the pandas Series values to a list is with the Python list() function.
list() tries to convert a Python object to a list. The list representation of a pandas Series is the values of the Series.
Below shows another example of how you can get the Series values of a pandas Series as a list in Python.
import pandas as pd df = pd.DataFrame() animal_types = list(df["animal_type"]) print(animal_types) #Output: ['dog', 'cat', 'dog', 'cat', 'dog', 'dog', 'cat', 'cat', 'dog']
Hopefully this article has been useful for you to be able to learn how to convert pandas Series to a list in Python.
Other Articles You’ll Also Like:
- 1. Set Widths of Columns in Word Document Table with python-docx
- 2. How to Multiply Two Numbers in Python
- 3. pandas tail – Return Last n Rows from DataFrame
- 4. Cartesian Product of Two Lists in Python
- 5. Using Python to Sum Odd Numbers in List
- 6. Python isfinite() Function – Check if Number is Finite with math.isfinite()
- 7. Python issuperset() Function – Check if Set is Superset of Another Set
- 8. Using Python to Remove Last Character from String
- 9. Python gethostbyname() Function – Get IPv4 Address from Name
- 10. pandas mad – Calculate Mean Absolute Deviation in Python
About The Programming Expert
The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.
Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.
At the end of the day, we want to be able to just push a button and let the code do it’s magic.
You can read more about us on our about page.