Pandas Series Object

Creating Series Object

In [1]:
import pandas as pd
from IPython.display import display

Create Series with Default Indexing

In [2]:
ds = pd.Series([1,2,3,4])
ds
Out[2]:
0    1
1    2
2    3
3    4
dtype: int64

Create Series with Explicit Indexing

In [3]:
ds = pd.Series([1,2,3,4], index=['a', 'b', 'c', 'd'])
ds
Out[3]:
a    1
b    2
c    3
d    4
dtype: int64

Create Series from dictionary

In [4]:
somedict = {
  "d":4,
  "a":1,
  "c":3,
  "b":2,
  "e":5
}
ds = pd.Series(somedict)

# note, that resulting Series is ordered by dictionary's sorted keys:
ds
Out[4]:
a    1
b    2
c    3
d    4
e    5
dtype: int64

Series Indexing

Get indexes

In [5]:
ds.index
Out[5]:
Index(['a', 'b', 'c', 'd', 'e'], dtype='object')

Retrieve elements by index

In [6]:
# numerical or keyword indexes: 
print(ds["a"])
print(ds[0])
1
1
In [7]:
# list indexes:
ds[['a', 'c', 'e']]
Out[7]:
a    1
c    3
e    5
dtype: int64
In [8]:
# slicing
ds["a":"d"]
Out[8]:
a    1
b    2
c    3
d    4
dtype: int64

Altering Series Index in place

In [9]:
ds
Out[9]:
a    1
b    2
c    3
d    4
e    5
dtype: int64
In [10]:
ds.index = ["A","B","C","D","E"]
ds
Out[10]:
A    1
B    2
C    3
D    4
E    5
dtype: int64

NumPy operations on Series

In [11]:
ds = pd.Series([1,2,3,4,5],index=["a","b","c","d","e"])
ds
Out[11]:
a    1
b    2
c    3
d    4
e    5
dtype: int64
In [12]:
# filtering by value
ds[ds>2]
Out[12]:
c    3
d    4
e    5
dtype: int64
In [13]:
ds*2
Out[13]:
a     2
b     4
c     6
d     8
e    10
dtype: int64

Dictionary like operation on Series

In [14]:
"a" in ds
Out[14]:
True
In [15]:
"f" in ds
Out[15]:
False

Missing data

In [16]:
ds1 = pd.Series([1,3], index=["a","c"])
ds2 = pd.Series([2,3], index=["b","c"])

print(ds1+ds2)
a    NaN
b    NaN
c    6.0
dtype: float64
In [17]:
ds = pd.Series([1,2,3])
ds
Out[17]:
0    1
1    2
2    3
dtype: int64