In this quick tutorial we’ll show how you can turn a series to a list of strings or numbers as needed.
Step 1: Create the Series
Let’s first and foremost create a Series that we will use as an example.
#Python3 # import the pandas library import pandas as pd # create a Series max_temp = pd.Series ([68.9, 68.9, 67.4, 68.9, 55]) # let's look into the series values print (max_temp)
0 68.9 1 68.9 2 67.4 3 68.9 4 55.0 dtype: float64
Let’s verify the Series type:
As expected the object type is a Pandas Series : pandas.core.series.Series
Step 2: Convert the Series using the to_list() Method.
Turning the Series to a list is quite simple here:
max_list = max_temp.to_list() print(max_list)
The result is as expected, a Python list.
[68.9, 68.9, 67.4, 68.9, 55.0]
Step 3: Manipulate the newly created list
You can obviously go ahead now and execute list operations on your newly created list; either directly or using a list comprehension.
max_list_celsius = [ round( (f-32)*(5/9),2) for f in max_list] print(max_list_celsius)
Our temperatures in celsius degrees:
[20.5, 20.5, 19.67, 20.5, 12.78]
Note: Although we exemplified this capability using a list of float numbers, you can employ the same logic to create a list of strings. A good example is when exporting your column index values to Python lists.
Export the Series index to a list
max_idx_list = max_temp.index.to_list() print(max_idx_list)
The result is as expected:
[0, 1, 2, 3, 4]