What is a Pandas Series?

What is a Pandas Series?

A Pandas Series is a one-dimensional labeled array that can hold any data type (integers, strings, floats, etc.). Think of it like a column in an Excel spreadsheet or a standalone list with superpowers—each element has a label (called an index) for easy access and manipulation.

import pandas as pd
d = [1, 7, 2]
var = pd.Series(d)
print(var)

Output
0    1
1    7
2    2
dtype: int64

Labels in Pandas Series

A Series automatically assigns numeric labels (indices) to each value if none are provided. These labels start at 0 and increment by 1 for each subsequent value, similar to Python lists.

import pandas as pd
data = ["apple", "banana", "cherry"]
series = pd.Series(data)
print(series)

Output
0     apple
1    banana
2    cherry
dtype: object

Creating Custom Labels in Pandas DataFrames

When working with Pandas DataFrames, you can assign custom labels to your rows using the index argument. This is particularly useful when you want more meaningful identifiers than the default numeric indices.

import pandas as pd
data = {'Name': ['John', 'Anna', 'Peter'],
'Age': [28, 24, 35]}


# Create DataFrame with custom labels
df = pd.DataFrame(data, index=['ID001', 'ID002', 'ID003'])

print(df)

Output
       Name  Age
ID001   John   28
ID002   Anna   24
ID003  Peter   35

Key Benefits: 🔑

  • Meaningful identifiers: Use business or natural keys instead of numbers
  • Easier data retrieval: Access rows by meaningful labels
  • Improved readability: Makes your data more understandable

Important Notes: 📋

  • Index labels must be unique
  • You can change labels later with df.index = new_labels
  • Consider using set_index() if your labels exist as a column

Creating Pandas Series from Key/Value Objects (Dictionaries)

You can create a Pandas Series directly from Python dictionaries, where the dictionary keys become the Series index and the values become the Series data values.

import pandas as pd

# Create Series from dictionary
data = {'A': 10, 'B': 20, 'C': 30}
series = pd.Series(data)
print(series)

Output

A    10
B    20
C    30
dtype: int64

Key Features: ðŸ”‘

  • Dictionary keys become index labels
  • Dictionary values become Series values
  • Preserves key-value relationships from the original dictionary

No comments

What is a Pandas Series?

What is a Pandas Series? A Pandas Series is a one-dimensional labeled array that can hold any data type (integers, strings, floats, etc.). T...

Powered by Blogger.