Get the specified row value of a given Pandas DataFrame
Last Updated :
17 Aug, 2020
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns).
Now let’s see how to get the specified row value of a given DataFrame.
We shall be using loc[ ], iloc[ ], and [ ] for a data frame object to select rows and columns from our data frame.
- iloc[ ] is used to select rows/ columns by their corresponding labels.
- loc[ ] is used to select rows/columns by their indices.
- [ ] is used to select columns by their respective names.
Method 1: Using iloc[ ].
Example: Suppose you have a pandas dataframe and you want to select a specific row given its index.
Python3
import pandas as pd
d = { 'sample_col1' : [ 1 , 2 , 3 ],
'sample_col2' : [ 4 , 5 , 6 ],
'sample_col3' : [ 7 , 8 , 9 ]}
df = pd.DataFrame(d)
print (df)
print ()
print (df.iloc[ 2 ])
|
Output:
Method 2: Using loc[ ].
Example: Suppose you want to select rows where the value of a given column is given.
Python3
import pandas as pd
d = { 'sample_col1' : [ 1 , 2 , 1 ],
'sample_col2' : [ 4 , 5 , 6 ],
'sample_col3' : [ 7 , 8 , 9 ]}
df = pd.DataFrame(d)
print (df)
print ()
print (df.loc[df[ 'sample_col1' ] = = 1 ])
|
Output:
Method 3: Using [ ] and iloc[ ].
Example: Suppose you want only the values pertaining to specific columns of a specific row.
Python3
import pandas as pd
d = { 'sample_col1' : [ 1 , 2 , 1 ],
'sample_col2' : [ 4 , 5 , 6 ],
'sample_col3' : [ 7 , 8 , 9 ]}
df = pd.DataFrame(d)
print (df)
print ()
print (df[[ 'sample_col1' , 'sample_col3' ]].iloc[ 1 ])
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...