How to Create Series in pandas: Simple Guide with Examples
You can create a
Series in pandas by passing a list, array, or dictionary to pd.Series(). Optionally, you can specify an index to label the data points.Syntax
The basic syntax to create a Series is pd.Series(data, index=index), where:
datacan be a list, array, or dictionary containing the values.indexis an optional list of labels for the data points.
python
import pandas as pd # Basic syntax series = pd.Series(data, index=index)
Example
This example shows how to create a Series from a list with custom index labels.
python
import pandas as pd # Create a Series from a list data = [10, 20, 30, 40] index = ['a', 'b', 'c', 'd'] series = pd.Series(data, index=index) print(series)
Output
a 10
b 20
c 30
d 40
dtype: int64
Common Pitfalls
Common mistakes include:
- Not providing an index when you want custom labels, which results in default numeric indexes.
- Passing a dictionary but expecting the order to be preserved (order depends on Python version and pandas version).
- Mixing data types unintentionally, which can cause dtype changes.
python
import pandas as pd # Wrong: expecting custom index but not providing it series_wrong = pd.Series([1, 2, 3]) print(series_wrong) # Right: providing index series_right = pd.Series([1, 2, 3], index=['x', 'y', 'z']) print(series_right)
Output
0 1
1 2
2 3
dtype: int64
x 1
y 2
z 3
dtype: int64
Quick Reference
| Parameter | Description |
|---|---|
| data | List, array, or dictionary of values |
| index | Optional list of labels for the Series |
| dtype | Optional data type for the Series |
| name | Optional name for the Series |
Key Takeaways
Use pd.Series() with data and optional index to create a Series.
Providing an index lets you label each data point clearly.
Data can be a list, array, or dictionary for flexible input.
Watch out for default numeric indexes if you don't specify labels.
Mixed data types can affect the Series data type automatically.