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:
Here is the Series object that we have constructed:
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:
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:
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)
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)