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??