Wednesday, October 6, 2021

DataFrame in Python - 6

1.

 #Add New Column in DataFrame using df['columnname']

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["IP"]=[25,30,32,21,22]

df["Maths"]=[22,20,22,31,32]

df["Total"]=df["IP"]+df["Maths"]

df["Pecentage"]=df["Total"]*100/70

print(df)


Output:


   Name  Roll No.
0   Ram        10
1   Raj        20
2   Sam        30
3  John        40
4  Amit        50
   Name  Roll No.  IP  Maths  Total  Pecentage
0   Ram        10  25     22     47  67.142857
1   Raj        20  30     20     50  71.428571
2   Sam        30  32     22     54  77.142857
3  John        40  21     31     52  74.285714
4  Amit        50  22     32     54  77.142857



2.
#Add New Column in DataFrame using insert() function

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.insert(2,"IP",[25,30,32,21,22])
df.insert(3,"Maths",[22,20,22,31,32])
df["Total"]=df["IP"]+df["Maths"]
df["Pecentage"]=df["Total"]*100/70
print(df)


Output:


   Name  Roll No.
0   Ram        10
1   Raj        20
2   Sam        30
3  John        40
4  Amit        50
   Name  Roll No.  IP  Maths  Total  Pecentage
0   Ram        10  25     22     47  67.142857
1   Raj        20  30     20     50  71.428571
2   Sam        30  32     22     54  77.142857
3  John        40  21     31     52  74.285714
4  Amit        50  22     32     54  77.142857



3.
Access a column from DataFrame using df['columnname'] and df.columnname

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['IP'])
print(df.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
0    25
1    30
2    32
3    21
4    22
Name: IP, dtype: int64




4.
#selecting a column from a DataFrame using 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['IP'])
print(df['Roll No.'])
print (df.iloc[:,[1,2]])


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
0    10
1    20
2    30
3    40
4    50
Name: Roll No., dtype: int64
   Roll No.  IP
0        10  25
1        20  30
2        30  32
3        40  21
4        50  22

No comments:

Post a Comment