Pandas Tutorial menu

Pandas Series

A Series is a single column of data where every value has a label.

Creating a Series From a List

Example

python
import pandas as pd

marks = pd.Series([78, 85, 62, 90])
print(marks)
Output
0    78
1    85
2    62
3    90
dtype: int64

The left column is the index (labels). The right column is the values. dtype is the data type.

Custom Labels

Give your own labels with index:

Example

python
import pandas as pd

marks = pd.Series([78, 85, 62], index=["Ali", "Sara", "Omar"])
print(marks)
print(marks["Sara"])
Output
Ali     78
Sara    85
Omar    62
dtype: int64
85

From a Dictionary

The keys become the labels automatically:

Example

python
import pandas as pd

prices = pd.Series({"tea": 70, "samosa": 40, "paratha": 80})
print(prices)
Output
tea        70
samosa     40
paratha    80
dtype: int64

Label or Position: loc and iloc

WayUsesExample
s.loc[label]The index labelprices.loc["tea"]
s.iloc[position]The position number (from 0)prices.iloc[0]

Example

python
import pandas as pd

prices = pd.Series({"tea": 70, "samosa": 40, "paratha": 80})
print(prices.loc["paratha"])
print(prices.iloc[1])
print(prices.iloc[0:2])
Output
80
40
tea       70
samosa    40
dtype: int64

Using loc and iloc makes it clear whether you mean a label or a position. This avoids confusion when labels are numbers too.

Maths on a Series

Like NumPy arrays, a Series works item by item:

Example

python
import pandas as pd

prices = pd.Series({"tea": 70, "samosa": 40, "paratha": 80})
print(prices * 2)
print(prices[prices > 50])
Output
tea        140
samosa      80
paratha    160
dtype: int64
tea        70
paratha    80
dtype: int64

Useful Series Methods

Example

python
import pandas as pd

sales = pd.Series([1200, 1500, 900, 1500, 1100])
print(sales.sum())
print(sales.mean())
print(sales.max())
print(sales.value_counts())
Output
6200
1240.0
1500
1500    2
1200    1
900     1
1100    1
Name: count, dtype: int64
MethodWhat it gives
sum(), mean(), median()Total, average, middle value
min(), max()Smallest and largest value
count()Number of non-empty values
value_counts()How often each value appears
unique()The distinct values
describe()A quick summary of all of the above

Giving a Series a Name

Example

python
import pandas as pd

s = pd.Series([31, 33, 29], name="temperature")
print(s.name)
Output
temperature

When you take one column out of a DataFrame, you get a Series named after that column.

Exercise

Exercise

s = pd.Series([10, 20, 30], index=["a", "b", "c"]). What does s.iloc[2] return?

Learn Pandas with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp