In This Section we will learn how to access the elements of a series like first “n” elements & Last “n” elements in python pandas. Access data from series with position in pandas. Access data from series using index We will be learning how to
- Accessing Data from Series with Position in python pandas
- Accessing first “n” elements & last “n” elements of series in pandas
- Retrieve Data Using Label (index) in python pandas
Accessing data from series with position:
Accessing or retrieving the first element:
Retrieve the first element. As we already know, the counting starts from zero for the array, which means the first element is stored at zeroth position and so on.
# create a series import pandas as pd import numpy as np data = np.array(['a','b','c','d','e','f']) s = pd.Series(data) #retrieve the first element print s[0]
output:
Access or Retrieve the first three elements in the Series:
# create a series import pandas as pd import numpy as np data = np.array(['a','b','c','d','e','f']) s = pd.Series(data) # retrieve first three elements print s[:3]
output:
1 b
2 c
Access or Retrieve the last three elements in the Series:
# create a series import pandas as pd import numpy as np data = np.array(['a','b','c','d','e','f']) s = pd.Series(data) # retrieve last three elements print s[-3:]
output:
4 e
5 f
dtype: object
Accessing data from series with Labels or index:
A Series is like a fixed-size dictionary in that you can get and set values by index label.
Retrieve a single element using index label:
# create a series import pandas as pd import numpy as np data = np.array(['a','b','c','d','e','f']) s = pd.Series(data,index=[100,101,102,103,104,105]) print s[102]
output:
Retrieve multiple elements using index labels:
# create a series import pandas as pd import numpy as np data = np.array(['a','b','c','d','e','f']) s = pd.Series(data,index=[100,101,102,103,104,105]) # retrieve multiple elements with labels or index print s[[102,103,104]]
output:
102 c
103 d
104 e
dtype: object
Note: If label or index is not mentioned properly an exception will be raised.