Python Pandas Series
A Series is a one-dimensional labeled array. It can hold any type of data like Integer, Float, String, Python objects, etc. The label is called the index.
How to create a Series
A series can be created using various inputs like-
- Array
- Dictionary
- constant
Create a Series from an array
If data is an array, then the index must be of the same length. If no index is passed, then by default index will be range(n) where n is the array length.
Example : 1.
#imports the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = np.array([‘a’,’b’,’c’,’d’,’e’])
sr=pd.Series(data)
print (sr)
Its output is as follows-
0 | a |
1 | b |
2 | c |
3 | d |
4 | e |
We did not pass any index. By default it assigned the index values ranging from 0 to 4, which is length(data) -1, i.e. 0 to 4.
Example : 2.
#imports the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = np.array([‘a’,’b’,’c’,’d’,’e’])
sr=pd.Series(data, index=[101,102,103,104,105])
print (sr)
Its output is as follows-
101 | a |
102 | b |
103 | c |
104 | d |
105 | e |
Create a Series from a dictionary
A dictionary can be passed as input and if no index is specified, then the dictionary keys are taken in a sorted order to construct the index.
Example :
#imports the pandas library and aliasing as pd
import pandas as pd
data = {‘a’ : 0, ‘b’ : 1, ‘c’ : 2, ‘d’ : 3}
sr=pd.Series(data)
print (sr)
Its output is as follows-
a | 0 |
b | 1 |
c | 2 |
d | 3 |
Create a Series from constant
An index must be provided if the data is a scalar value or constant. The value will be repeated to match the length of the index.
Example :
#imports the pandas library and aliasing as pd
import pandas as pd
import numpy as np
sr=pd.Series(4, index=[0,1,2,3])
print (sr)
Its output is as follows-
0 | 4 |
1 | 4 |
2 | 4 |
3 | 4 |