A Pandas Series can be created from different Python data structures like
lists, dictionaries, and NumPy arrays.
This flexibility makes it easy to bring existing data into Pandas for analysis.
๐น Creating Series from a List
When you pass a Python list to pd.Series(), Pandas creates a Series with a default integer index starting from 0.
import pandas as pd
data = [10, 20, 30, 40]
s = pd.Series(data)
print(s)
๐ Output:
0 10
1 20
2 30
3 40
dtype: int64
๐น Creating Series with Custom Index
s = pd.Series([10, 20, 30], index=["a", "b", "c"])
print(s)
๐ Output:
a 10
b 20
c 30
dtype: int64
๐น Creating Series from a Dictionary
When using a dictionary, the keys become the index, and the values become the data.
data = {"x": 100, "y": 200, "z": 300}
s = pd.Series(data)
print(s)
๐ Output:
x 100
y 200
z 300
dtype: int64
๐น Creating Series from a NumPy Array
Pandas works closely with NumPy, so you can directly create a Series from a NumPy array.
import numpy as np
arr = np.array([5, 10, 15, 20])
s = pd.Series(arr, index=["A", "B", "C", "D"])
print(s)
๐ Output:
A 5
B 10
C 15
D 20
dtype: int64
No comments:
Post a Comment