In this tutorial, we will learn how to convert the pandas series to a list in Python. The list provides easy iteration and is convenient to use in most of the scenarios.
.tolist() function
If you load the dataset using the Pandas library and then check the data type of the columns in which it gets stored, you will notice that it is pandas.core.series.Series. So, if you want to convert this data type to the list type, you can use the Pandas .tolist()
function.
import pandas as pd df = pd.read_csv("data/Data.csv") df
I have loaded a random dataset from my laptop. Look at the dataset, we will convert the ‘Country’ column values into a list. I will print the data type before and after converting it into the list data type.
print(df['Country']) print(type(df['Country']))
0 France 1 Spain 2 Germany 3 Spain 4 Germany 5 France 6 Spain 7 France 8 Germany 9 France Name: Country, dtype: object <class 'pandas.core.series.Series'>
As you can see, the initial data type of the column values is pandas.core.series.Series. Now, we will convert it into a list datatype.
country_list = df['Country'].tolist() print(country_list) print(type(country_list))
['France', 'Spain', 'Germany', 'Spain', 'Germany', 'France', 'Spain', 'France', 'Germany', 'France'] <class 'list'>
If you want to learn how to convert the datatype to the series, check the <Create a pandas series from a dictionary of values and an ndarray> Tutorial link.