The tolist()
method in Pandas is used to convert a Series to a Python list.
Example
import pandas as pd
# create a Series
series_data = pd.Series([1, 2, 3, 4, 5])
# convert the Series to a list
list_data = series_data.tolist()
print(list_data)
# Output: [1, 2, 3, 4, 5]
tolist() Syntax
The syntax of the tolist()
method in Pandas is:
Series.tolist()
tolist() Return Value
The tolist()
method returns a new list containing the data from the original Series.
Example 1: Convert Series to a list
import pandas as pd
# create a Series
series_data = pd.Series([10, 20, 30, 40, 50])
# convert the Series to a list using tolist()
list_data = series_data.tolist()
print(list_data)
Output
[10, 20, 30, 40, 50]
In the above example, we have created the Series named series_data with integers
We then used the tolist()
method to convert the series_data Series into a Python list.
Example 2: Convert Series with Mixed Data Types to a List
import pandas as pd
# create a Series with mixed data types
mixed_series = pd.Series([1, 'two', 3.0, 'four'])
# convert series to a list
mixed_list = mixed_series.tolist()
print(mixed_list)
Output
[1, 'two', 3.0, 'four']
Here, we have created the Series named mixed_series containing a mix of integers, strings, and a float.
Then we converted this mixed_series into the list named mixed_list using mixed_series.tolist()
.
Example 3: Convert Series With DateTime to a List
import pandas as pd
# create a Series with DateTime data
date_series = pd.Series(pd.date_range('2023-01-01', periods=3, freq='D'))
# convert date_series series to list
date_list = date_series.tolist()
print(date_list)
Output
[Timestamp('2023-01-01 00:00:00'), Timestamp('2023-01-02 00:00:00'), Timestamp('2023-01-03 00:00:00')]
In this example, we have created the Series named date_series that contains a range of dates.
Here, the pd.date_range()
method is used to generate a sequence of dates starting from January 1, 2023, 2023-01-01
, and creating a total of 3 dates, periods=3
, with a daily frequency, freq='D'
.
Then, we converted date_series into a Python list using the tolist()
method. This list contains the dates as pandas Timestamp
objects.