How to Create a Pandas Series from Python Lists

Last updated on August 30, 2022 Augustus Loading... Post a comment

A Pandas Series is a one-dimensional arraylike object holding a sequence of values of any type and an associated array of data labels (index). You can create a Pandas Series from one or multiple Python lists by using the pd.Series class.

Construct a Pandas Series from a single Python list

Example:

import pandas as pd

# Create a Series from a single Python list
numbers = pd.Series([1, 2, 3, 4, 5])
print(type(numbers))
print(numbers)

Output:

<class 'pandas.core.series.Series'>
0    1
1    2
2    3
3    4
4    5
dtype: int64

Construct a Pandas Series from many Python lists

If you have more than one list and your goal is to form a Pandas Series from them, just use the addition (+) operator, like this:

import pandas as pd

fruits =  ['apple', 'orange', 'banana']
animals = ['dog', 'cat', 'rabbit']
projects = ['kindacode.com', 'www.kindacode.com']

things = pd.Series(fruits + animals + projects)
print(things)

Output:

0                apple
1               orange
2               banana
3                  dog
4                  cat
5               rabbit
6        kindacode.com
7    www.kindacode.com
dtype: object

Setting your own labels

If you only specify the input lists, the values are labeled with their index number (0, 1, 2, 3, and so on). To name your own labels, add an argument for the index parameter, like so:

import pandas as pd

series = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
print(series)

Output:

a    1
b    2
c    3
d    4
dtype: int64

Further reading:

You can also check out our Python category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like