Series in Pandas
In this class, We discuss Series in Pandas.
For Complete YouTube Video: Click Here
Series
A series is a one-dimensional labeled array capable of holding any data type.
In our previous classes, we discussed data frames. The data frame is a two-dimensional array capable of holding any type.
The reader should have prior knowledge of the data frame. Because most of the methods and attributes are similar, click here.
First, we do examples of creating a series.
Creating a Series
The example of creating Series is given below.
import numpy as np
import pandas as pd
data=np.array([1,2,3])
series=pd.Series(data)
print(series)
Output:
0 1
1 2
2 3
dtype: int32
In our example, we have taken a numpy array.
The array is given as input to the function Series. The function series is used to create a series object.
After creating a series, we can apply the attributes and methods present in the Series. Click here.
We are not explaining the attributes and methods in the Series because most of them are discussed in a data frame in previous classes.
Similar methods are present here.
index in Series
We can assign our index to the Series using the index parameter in the series class.
The example is shown below.
data=[1,'h',8]
series=pd.Series(data,index=['a','b','c'])
print(series)
Output:
a 1
b h
c 8
dtype: object
In our example, we are giving index values a,b,c.
We can access the elements of the Series using the loc method. The same way we did in the data frame. Click here.
Series using Dictionaries
The example is shown below.
d = {'a': 1, 'b': 2, 'c': 3}
series = pd.Series(data=d)
print(series)
Output:
a 1
b 2
c 3
dtype: int64
We take a dictionary. The key values are taken as an index in the Series.
In our example, a,b,c are considered index values.
One important point we have to understand. In the data frame, if we take a column. The column values are considered as a series object.
The example is shown below.
import pandas as pd
df = pd.DataFrame([[1, 2, 3],[4, 5, 6],[7, 8, 9]],columns=['A', 'B', 'C'])
print(df)
x=df['A']
print(type(x))
print(x.iloc[0])
Output:
A B C
0 1 2 3
1 4 5 6
2 7 8 9
<class 'pandas.core.series.Series'>
1
We have taken column A in the data frame and displayed the type. The type is shown as a series object.
We accessed the elements in column A using the iloc method.
Suppose we consider the row of a data frame. The row is taken as a series object.
The example is shown below.
x=df.loc[0]
print(type(x))
print(x.loc['C'])
Output:
<class 'pandas.core.series.Series'>
3