Introduction to Pandas
Chapter 2: Series
Creating a Series instance
Here is how you create a basic Series
instance.
>>> series = pd.Series(data=["UK", "France", "Italy"])
>>> print(series)
0 UK
1 France
2 Italy
dtype: object
You can also pass in the name of the Series
to the constructor.
>>> series = pd.Series(data=["UK", "France", "Italy"], name="country")
>>> print(series)
0 UK
1 France
2 Italy
Name: country, dtype: object
As you may have noticed, pandas automatically assigns a sequence starting from 0 as the index (or axis labels) for your data. To customise this, just pass it to the constructor!
>>> series = pd.Series(data=["UK", "France", "Italy"],
... index=["a", "b", "c"],
... name="country")
>>> print(series)
a UK
b France
c Italy
Name: country, dtype: object
You can also pass in the dtype
keyword argument, which acts just like in NumPy
.
Interestingly, you can have duplicate index
labels. But this is best avoided. Python will eventually complain anyway when it attempts an operation that does not support duplicate index values. Apparently this is allowed purely for performance reasons.