QnA – Select Access data from Dataframe

 Q – 1 What are the way to select or access data from a dataframe?

Ans.: You can select or access data from a dataframe in following ways:

    1. Using column name(s)
    2. Using .net notation
    3. Using loc[]
    4. Using iloc[]
    5. Using slicing
    6. Individual Value using at[] & iat[]

Q -2 Consider the folloowing dataframe and do as directed:

import pandas as pd

d={‘Mouse’:[150,200,300,400],

   ‘Keyboard’:[180,200,190,300],

   ‘Scanner’:[200,280,330,450]}

df=pd.DataFrame(d,index=[‘Jan’,’Feb’,’March’,’April’])

A. Write code to access data of Mouse and Scanner columns.

print(df[[‘Mouse’,’Scanner’]])

B. Write code to access data of the Keyboard column using dot notation and column name.

print(df.Keybaord)

C. Write code to access data of scanners using loc[].

print(df.loc[:,’Scanner’])

D. Write code to access data of all columns where mouse data is more than 200.

print(df[df[‘Mouse’]>200])

E. Write code to access columns using 0 and 2.

print(df.iloc[:,[0,2]])

F. Write code to access data of rows of jan and march for scanner and keyboard.

print(df.loc[[‘Jan’,’March’],[‘Scanner’,’Keyboard’]])

  • Consider the above dataframe and predict the output:

a)       print(df.iloc[1][2]) → 280

b)      print(df.loc[‘Feb’,’Scanner’]) →  280

c)       df1=df[df[‘Keyboard’]>190] 

       print(df1[[‘Mouse’,’Scanner’]])      Mouse  Scanner

                                                        Feb      200      280

                                                        April    400      450

d)      print(df.iat[2,1]) → 190

  •         Consider the above dataframe and find out errors in following code fragment:

a.       df[1,3] èCorrection: df.iloc[:,[1.3]]

b.       df.loc[2,2] èCorrection: loc needs index of row and column, df.loc[‘March’,’Scanner’]

c.       df.at[1][1]èCorrection: at also required coloumn name, df.at[‘Feb’,’Keyboard’]

d.       df.iloc[0;2,1] èCorrection: Semicolon will be replaced with :, df.iloc[0:2,1]

  •        Explain following code lines in your words, what it will do:

a. df.iloc[:2,] → It will access row indexes from 0:2 (exclude 2) and all columns of dataframe.

b. df.loc[:,’Mouse’] → It will access mouse data with all rows.

c. df.at[‘March’,’Scanner’] → Access Scanner details of March Month.

d. df.iloc[2,0] → Access the value located at row index 2 (‘Macrh’) and column index 0 (Mouse)

e.       df.iloc[0:2,0:1] → It will access rows ranges 0 to 2 and columns 0 to 1 excluding upper limit index number.

f.        df.iloc[:,2] → Access all rows and column index 2.


Q – 3 What is the difference between loc[] and iloc[]?

Ans.: Both are used to access data from dataframe with a list of rows and columns. Loc requires columns names whereas iloc requires index number.
Q – 4 What is the difference between at[] and iat[]?
Ans.: Similar as above only just replace the words loc[] and iloc[] with at[] and iat[].

Comment Your Views

%d bloggers like this: