Series in Pandas
Pandas Series Explained
A Pandas Series is a one-dimensional labeled array that can hold data of any type, including integers, floats, strings, and even Python objects. It is similar to a column in a spreadsheet or a list in Python, but with additional functionalities like indexing and vectorized operations.
Creating a Pandas Series
To create a Series, first import Pandas:
import pandas as pd
1. Creating a Series from a List
data = [10, 20, 30, 40]
series = pd.Series(data)
print(series)
Output:
0 10
1 20
2 30
3 40
dtype: int64
- The left column (0, 1, 2, 3) is the index.
- The right column (10, 20, 30, 40) is the data.
2. Creating a Series with Custom Index By default, Pandas assigns numeric indices (0, 1, 2, …), but you can define custom index labels:
data = [100, 200, 300]
index_labels = ["A", "B", "C"]
series = pd.Series(data, index=index_labels)
print(series)
Output:
A 100
B 200
C 300
dtype: int64
Now, instead of numeric indices, we have labels A, B, and C.
3. Creating a Series from a Dictionary You can also create a Series using a dictionary:
data = {"Apple": 50, "Banana": 30, "Cherry": 40}
series = pd.Series(data)
print(series)
Output:
Apple 50
Banana 30
Cherry 40
dtype: int64
- The dictionary keys become index labels, and values become the Series data.
Accessing Elements in a Series
1. Accessing Data Using Index
print(series["Apple"]) # Output: 50
print(series[0]) # Output: 50 (if default integer index is used)
2. Slicing a Series
print(series[0:2]) # Select first two elements
3. Filtering Data
print(series[series > 30]) # Filter elements greater than 30
Performing Operations on a Series
Pandas Series supports vectorized operations, meaning you can perform operations on all elements without using loops.
1. Mathematical Operations
print(series * 2) # Multiply all values by 2
print(series + 10) # Add 10 to all values
2. Checking for Missing Values
print(series.isnull()) # Returns True for NaN values
3. Applying Functions
print(series.apply(lambda x: x * 2)) # Multiply each value by 2
When to Use a Series?
- When working with single-column data.
- When performing mathematical operations on a single dataset.
- When handling one-dimensional labeled data, like time series or stock prices.