How to Select Row and Column in Pandas DataFrame || Python for Informatics Practices Class 12th

How to Select Row and Column in Pandas DataFrame

1. Selecting Column From Pandas DataFrame

We can select only one column instead of selecting the whole DataFrame.
Example.1 

import pandas as pd
data = { ‘first’ : pd.Series( [ 1,2,3,4,5 ], index= [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] ),
‘second’ : pd.Series( [ 10,20,30,40,50 ], index= [ ‘a’, ‘b’, ‘c’, ‘d’, ‘e’ ] )  }
df=pd.DataFrame(data)
print (df [‘first’])

Its output will be
        first
      一一一
a        1
b        2
c        3
d        4
e        5
Note:- You can see DataFrame has two columns ‘first’ and ‘second’ but the output shows only one column. If DataFrame has a number of columns we can select any column randomly.
Example.2

import pandas as pd
data = { ‘first’ : pd.Series( [ 1,2,3,4,5 ], index= [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] ),
‘second’ : pd.Series( [ 10,20,30,40,50 ], index= [ ‘a’, ‘b’, ‘c’, ‘d’, ‘e’ ] )  }
df=pd.DataFrame(data)
print (df [‘second’])

Its output will be
      second
一一一
a        10
b        20
c        30
d        40
e        50

2. Selecting Row From Pandas DataFrame

We can also select only one or more rows instead of selecting the whole Pandas DataFrame.
Example.1:-  A Row can be selected by passing the index or label to loc() function

import pandas as pd
data = { ‘first’ : pd.Series( [ 1,2,3,4,5 ], index= [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] ),
‘second’ : pd.Series( [ 10,20,30,40,50 ], index= [ ‘a’, ‘b’, ‘c’, ‘d’, ‘e’ ] )  }
df=pd.DataFrame(data)
print (df.loc[ ‘d’ ])

Its output will be
first         4
second    40
Note:- The result shows data of row label ‘d’.
Example.2:-  Any Row can be selected by passing integer location to iloc() function

import pandas as pd
data = { ‘first’ : pd.Series( [ 1,2,3,4,5 ], index= [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] ),
‘second’ : pd.Series( [ 10,20,30,40,50 ], index= [ ‘a’, ‘b’, ‘c’, ‘d’, ‘e’ ] )  }
df=pd.DataFrame(data)
print (df.iloc[ 2 ])

Its output will be
first         3
second    30
Note:- The result shows data of row at number 3.
Example.3:- If we want to select more than one row. Multiple numbers of  Rows can be selected by using ‘ : ‘ operator

import pandas as pd
data = { ‘first’ : pd.Series( [ 1,2,3,4,5 ], index= [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] ),
‘second’ : pd.Series( [ 10,20,30,40,50 ], index= [ ‘a’, ‘b’, ‘c’, ‘d’, ‘e’ ] )  }
df=pd.DataFrame(data)
print (df [ 3 : 5 ])

Its output will be
          first      second
d          4            40
e          5            50
If you like my post please share it with your friends by simply clicking the below social media button, and don’t forget to comment so we will update ourselves.
Share in a Single Click

Leave a Reply

Your email address will not be published. Required fields are marked *