In this tutorial we’ll learn how to use Python in order to convert a Pandas Series object to a Python list. We’ll then explore additional cases such as casting a list to a Set and to a Numpy array.
Creating an Example Series object
Let’s start by creating some example data:
# import the Pandas library into your Python environment
import pandas as pd
# define list
names = ['C-Sharp', 'Go', 'Java', 'Javascript',
'Javascript']
# use Pandas to create a series
languages = pd.Series(names)
print(languages.head())
Here is the Series object that we have constructed:
0 C-Sharp 1 Go 2 Java 3 Javascript 4 Javascript dtype: object
Convert Series to list
In order to convert our Series to a list, we use the Series method to_list(); as shown below:
lang_lst = languages.values.tolist()
print(languages_lst)
Here’s our list of strings:
['C-Sharp', 'Go', 'Java', 'Javascript',
'Javascript']
Series to list with index
Next, we would like to go ahead and convert the Series index to a list and then zip it with the Series values list that we have exported in the previous step.
lang_idx_list = languages.index.tolist()
print(lang_idx_list)
This will result in the following:\ list
[0, 1, 2, 3, 4]
Now we can go ahead and zip the Series index and value lists, to a list of tuples:
merge_lang_list = list(zip(lang_idx_list,lang_lst))
print(merge_lang_list)
Here’s the result:
[(0, 'C-Sharp'), (1, 'Go'), (2, 'Java'), (3, 'Javascript'), (4, 'Javascript')]
Pandas Series to Python set
As needed, we can convert our Series to a Python set. THis is helpful for example, if we would like to find unique occurrences in the Series. Here’s a simple example:
languages_set = set(languages.tolist())
print(languages_set)
{'Javascript', 'Go', 'Java', 'C-Sharp'}
Pandas Series to Numpy Array
Converting a Series object to a Numpy array is relatively simple with the to_numpy Series method.
lang_array = pd.Series.to_numpy(languages)