Python ProgrammingPython Programming

How to create a pandas Series using lists and dictionaries?

Creating Series using list:

import pandas as pd

ser1 = pd.Series([1.5, 2.5, 3, 4.5, 5.0, 6])
print(ser1)

The output shows two columns, first column of numbers which represents the index of the Series and the second column contains the values. dtype: float64 represents that the data type of the values in the Series is float64.

C:\python\pandas examples>python example1.py
0    1.5
1    2.5
2    3.0
3    4.5
4    5.0
5    6.0
dtype: float64

Creating Series of string values with name:

import pandas as pd

ser2 = pd.Series(["India", "Canada", "Germany"], name="Countries")
print(ser2)

Here, we have given a name as Countries to the Series.

C:\python\pandas examples>python example2.py
0      India
1     Canada
2    Germany
Name: Countries, dtype: object

Python shorthand for list creation used to create Series:

import pandas as pd

ser3 = pd.Series(["A"]*4)
print(ser3)

Here, the Series consist of a sequence of 4 identical values "A".

C:\python\pandas examples>python example3.py
0    A
1    A
2    A
3    A
dtype: object

Creating Series using dictionary:

import pandas as pd

ser4 = pd.Series({"India": "New Delhi",
                  "Japan": "Tokyo",
                  "UK": "London"})
print(ser4)

The keys of the dictionary are used to represents the index of the Series.

C:\python\pandas examples>python example4.py
India    New Delhi
Japan        Tokyo
UK          London
dtype: object