Tuesday, October 5, 2021

DataFrame in Python - 5

1. 

Add New Row in DataFrame 

import pandas as pd

D={'Name':['ritu','ajay','pankaj','aditya'],'English':[67,78,75,88],'Bio':[78,67,89,90],'Physics':[34,45,67,78],'Chem':[23,32,67,87]}

df=pd.DataFrame(D)

print(df)

#Add New Row in DataFrame

df.loc['4']={'Name':'udai','English':55 ,'Bio':98,'Physics':89 ,'Chem':56}

print(df)


Output:


========== RESTART: C:\Users\acer\AppData\Local\Programs\Python\Python39\DF4.py ==========
     Name  English  Bio  Physics  Chem
0    ritu       67   78       34    23
1    ajay       78   67       45    32
2  pankaj       75   89       67    67
3  aditya       88   90       78    87
     Name  English  Bio  Physics  Chem
0    ritu       67   78       34    23
1    ajay       78   67       45    32
2  pankaj       75   89       67    67
3  aditya       88   90       78    87
4    udai       55   98       89    56



2. 
Modify the row in DataFrame


import pandas as pd
D={'Name':['ritu','ajay','pankaj','aditya'],'English':[67,78,75,88],'Bio':[78,67,89,90],'Physics':[34,45,67,78],'Chem':[23,32,67,87]}
df=pd.DataFrame(D)
print(df)
#modify the row
df.loc[1]=["ajay",61,62,63,64]
print(df)


Output:



 ==========
     Name  English  Bio  Physics  Chem
0    ritu       67   78       34    23
1    ajay       78   67       45    32
2  pankaj       75   89       67    67
3  aditya       88   90       78    87
     Name  English  Bio  Physics  Chem
0    ritu       67   78       34    23
1    ajay       61   62       63    64
2  pankaj       75   89       67    67
3  aditya       88   90       78    87
>>> 



3.
Rename the column in DataFrame

import pandas as pd
D=[10,20,30,40,50]
df=pd.DataFrame(D)
print(df)
df.columns=["Roll No."]
print(df)



Output:

    0
0  10
1  20
2  30
3  40
4  50
   Roll No.
0        10
1        20
2        30
3        40
4        50


4. 
Rename Multiple columns in DataFrame


import pandas as pd
D={"Name":["Ram","Raj","Sam","John","Amit"],"Roll No.":[10,20,30,40,50]}
df=pd.DataFrame(D)
print(df)
df.columns=["Std_Name","Std_id"]
print(df)

Output:


   Name  Roll No.
0   Ram        10
1   Raj        20
2   Sam        30
3  John        40
4  Amit        50
  Std_Name  Std_id
0      Ram      10
1      Raj      20
2      Sam      30
3     John      40
4     Amit      50





import pandas as pd
D={"Name":["Raju","Raj","Ram"],"IP":[30,32,28],"Bio":[25,28,32]}
df=pd.DataFrame(D)
print(df)
df.rename(columns={"Bio":"Biology","IP":"Informatics Practices"},inplace=True)
print(df)



   Name  IP  Bio
0  Raju  30   25
1   Raj  32   28
2   Ram  28   32
   Name  Informatics Practices  Biology
0  Raju                     30       25
1   Raj                     32       28
2   Ram                     28       32


No comments:

Post a Comment