The python pandas series object is similar to the list object, it contains an index ( or tag ) and related values. This article will show you some examples of how to use it in python.
1. How To Create A Pandas Series Object.
1.1 Use pandas.Series(data, index=index) method.
- When the data parameter is a multi-dimensional array, the index length must be consistent with the data length.
- If the index parameter is not specified, a numerical index will be automatically created (minus 1 from the data parameter’s length)
import pandas as pd s1 = pd.Series(['a', 'b', 3]) print(s1) ======================================= Output: 0 a 1 b 2 3 dtype: object
1.2 Use The Series Class From The Python Pandas Module.
- If you import the Series class from the pandas module, you can create Series objects directly in your program.
from pandas import Series s2 = Series([7, 8, 9]) print(s2) =================================== Output: 0 7 1 8 2 9 dtype: int64
2. Series Index.
- Config Series object index manually.
import pandas as pd s3 = pd.Series(['80', '90', '100'], index=['c++', 'java', 'python']) print(s3) ============================================================== Output: c++ 80 java 90 python 100 dtype: object
- Get elements in Series object by location index.
import pandas as pd s3 = pd.Series(['80', '90', '100'], index=['c++', 'java', 'python']) print(s3) print('s3[0] = ', s3[0]) ========================================================================== Output: c++ 80 java 90 python 100 dtype: object s3[0] = 80
- Series label index.
import pandas as pd s3 = pd.Series(['80', '90', '100'], index=['c++', 'java', 'python']) print(s3) print("s3['python'] = ", s3['python']) ============================================================================ Output: c++ 80 java 90 python 100 dtype: object s3['python'] = 100
- Series slice index.
import pandas as pd s3 = pd.Series(['80', '90', '100'], index=['c++', 'java', 'python']) print("s3['c++':'java'] = \n", s3['c++':'java']) ============================================================== Output: s3['c++':'java'] = c++ 80 java 90 dtype: object
- Get Series data through index slicing.
import pandas as pd s4 = pd.Series(['a','b','c','d','e','f','g']) print("s4[1:5] =\n", s4[1:5]) ======================================================= Output: s4[1:5] = 1 b 2 c 3 d 4 e dtype: object
- Get Series object index and values.
import pandas as pd s5 = pd.Series(['Hello','World','I','Love','Python']) print('s5.index = ', s5.index) print('s5.values = ', s5.values) s6 = pd.Series(['Hello','World','I','Love','Python'], index=['a','b','c','d','e']) print('s6.index = ', s6.index) print('s6.values = ', s6.values) =========================================================================================== Output; s5.index = RangeIndex(start=0, stop=5, step=1) s5.values = ['Hello' 'World' 'I' 'Love' 'Python'] s6.index = Index(['a', 'b', 'c', 'd', 'e'], dtype='object') s6.values = ['Hello' 'World' 'I' 'Love' 'Python']