Pandas Series: The Complete Guide

Pandas Series is a “one-dimensional data structure capable of carrying data of any type like integer, string, float, python objects, etc.”

Syntax

pandas.Series( data, index, dtype, copy)

Parameters

  1.  data: It takes various forms like ndarray, list, and constants.
  2. index: The values must be unique and hashable, the same length as the data.
  3. dtype: It is for the data type. If None, the data type will be inferred.
  4. copy: It is to copy the data. The default parameter is False.

Creating a Series

import pandas as pd
import numpy as np

data = np.array(['a','b','c','d'])
seri = pd.Series(data)
print(seri)

In the above example, we have imported two libraries which are Pandas and Numpy.

Then we used NumPy to construct the data, passed that to the series function of pandas, and created a series.

Output

Python Pandas Series Tutorial

Creating an empty series

A primary series that can be created is an Empty Series.

import pandas as pd

seri = pd.Series()
print(seri)

Output

Create an Empty Series

Constructing Series from a list with copy=False

import pandas as pd

data = [11, 19, 21]

ser = pd.Series(data, copy=False)

ser.iloc[0] = 99

print(ser)

Output

0  99
1  19
2  21

dtype: int64

Constructing Series from a 1D ndarray with copy=False

import pandas as pd
import numpy as np

data = np.array([11, 21, 19])
ser = pd.Series(data, copy=False)

ser.iloc[0] = 99
print(ser)

Output

0   99
1   21
2   19

dtype: int64

Accessing an element of Series

Here are two ways through which we can access elements of the Series, they are:

  1. Accessing Element from Series with Position
  2. Accessing Element Using Label (index)

Accessing Element from Series with Position

Use the “index operator [ ]” to access an element in a Series.

import pandas as pd

# Create a Series with index labels
s = pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd'])

# Accessing element using index label
value_by_index = s['b']

print("Value by index label:", value_by_index)

Output

Value by index label: 20

Accessing Element Using Label (index)

You can use the “iloc” attribute to access an element by its integer location.

import pandas as pd

# Create a Series with index labels
s = pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd'])

value_by_position = s.iloc[1]

print("Value by index label:", value_by_position)

Output

Value by index label: 20

Binary Operation on Series in Pandas

Binary operations can be performed on pandas Series objects to combine them element-wise. These operations are aligned on the index labels so that you can combine Series objects with different index labels, and pandas will handle the alignment for you.

Here are some examples of binary operations you can perform on the Pandas Series:

  1. Addition: Combines two Series using the “+ operator.”
  2. Subtraction: Combines two Series using the “- operator.”
  3. Multiplication: Combines two Series using the “* operator.”
  4. Division: Combines two Series using the “/ operator.”
import pandas as pd

# Create two Series with some overlapping index labels
s1 = pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd'])
s2 = pd.Series([5, 15, 25, 35], index=['b', 'c', 'd', 'e'])

# Perform binary operations
addition = s1 + s2
subtraction = s1 - s2
multiplication = s1 * s2
division = s1 / s2

print("Addition:")
print(addition)
print("\nSubtraction:")
print(subtraction)
print("\nMultiplication:")
print(multiplication)
print("\nDivision:")
print(division)

Output

Binary Operation on Series in Pandas

Conversion Operation on Series

Convert to a Different Data Type

You can use the astype() method to convert the data type of a Series. For example, you can convert a Series of strings to floats:

import pandas as pd

s = pd.Series(['1.1', '2.2', '3.3'])

s_float = s.astype(float)

print(s_float)

Output

Convert to a Different Data Type

Convert to DateTime

If you have a Series containing dates as strings, you can convert them to datetime objects:

import pandas as pd

s = pd.Series(['2021-01-01', '2021-02-01', '2021-03-01'])

s_datetime = pd.to_datetime(s)

print(s_datetime)

Output

0 2021-01-01
1 2021-02-01
2 2021-03-01

dtype: datetime64[ns]

Apply a Custom Function

You can use the apply() method to apply a custom function to each element in the Series:

import pandas as pd

s = pd.Series([1, 2, 3, 4])

s_squared = s.apply(lambda x: x**2)

print(s_squared)

Output

0   1
1   4
2   9
3   16

dtype: int64

Related posts

Pandas Series value_counts()

Pandas Series unique()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.