Wednesday, August 27, 2025

🐍Creating Series from lists, dicts and arrays

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
    

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??