Thursday, October 7, 2021

DataFrame iloc, loc, del, drop, pop in Python - 7

# Using loc and iloc 

 import pandas as pd

D={"Name":["Ram","Raj","Sam","John","Amit"],"Roll No.":[10,20,30,40,50], \

   "IP":[25,30,32,21,22]}

df=pd.DataFrame(D)

print(df)

print(df.iloc[1:3])

print(df.loc[1:3])


Output:

Name  Roll No.  IP

0   Ram        10  25

1   Raj        20  30

2   Sam        30  32

3  John        40  21

4  Amit        50  22

  Name  Roll No.  IP

1  Raj        20  30

2  Sam        30  32

   Name  Roll No.  IP

1   Raj        20  30

2   Sam        30  32

3  John        40  21



#Using of pop in DataFrame

import pandas as pd

D={"Name":["Ram","Raj","Sam","John","Amit"],"Roll No.":[10,20,30,40,50], \

   "IP":[25,30,32,21,22]}

df=pd.DataFrame(D)

print(df)

print (df.pop('IP'))



Output:

Name  Roll No.  IP

0   Ram        10  25

1   Raj        20  30

2   Sam        30  32

3  John        40  21

4  Amit        50  22

0    25

1    30

2    32

3    21

4    22

Name: IP, dtype: int64


#Using drop in DataFrame

import pandas as pd

D={"Name":["Ram","Raj","Sam","John","Amit"],"Roll No.":[10,20,30,40,50], \

   "IP":[25,30,32,21,22]}

df=pd.DataFrame(D)

print(df)

print (df.drop('Name',axis=1))



Output:


Name  Roll No.  IP

0   Ram        10  25

1   Raj        20  30

2   Sam        30  32

3  John        40  21

4  Amit        50  22

Roll No.  IP

0        10  25

1        20  30

2        30  32

3        40  21

4        50  22


#Using del in DataFrame

import pandas as pd

D={"Name":["Ram","Raj","Sam","John","Amit"],"Roll No.":[10,20,30,40,50], \

   "IP":[25,30,32,21,22]}

df=pd.DataFrame(D)

print(df)

del df['Name']

print(df)



Output:


Name  Roll No.  IP

0   Ram        10  25

1   Raj        20  30

2   Sam        30  32

3  John        40  21

4  Amit        50  22

Roll No.  IP

0        10  25

1        20  30

2        30  32

3        40  21

4        50  22

No comments:

Post a Comment