Professional Documents
Culture Documents
16 Advanced Operations On Dataframe
16 Advanced Operations On Dataframe
PIVOTING:
It rearranges the data from rows and columns by possibly rotating
rows and columns or by aggregating data from multiple sources in a
report form.
The arguments of Pivot() function are
i. Index – stores the column name about which the information is to
be summarised(will become rows in the result)
ii. Columns- stores the column name whose data will become a
column each in the summary information(will become columns in
the result)
iii. Values- stores the column name whose data will be displayed
for the index, column combination( will become cells in the result)
import pandas as pd
d1={'students':['Arun','Neha','Supreet','Usha','Mukesh'],'marks':
[78.5,83.4,65.6,92.2,88.6], 'sport':
['Cricket','Badminton','Football','Atheletics','Kabaddi']}
df1=pd.DataFrame(d1)
print(df1)
students marks sport
0 Arun 78.5 Cricket
1 Neha 83.4 Badminton
2 Supreet 65.6 Football
3 Usha 92.2 Atheletics
4 Mukesh 88.6 Kabaddi
After pivoting
import pandas as pd
d1={'students':['Arun','Neha','Supreet','Usha','Mukesh'],'marks': [78.5,83.4,65.6,92.2,88.6],
'sport':['Cricket','Badminton','Football','Atheletics','Kabaddi']}
df1=pd.DataFrame(d1)
print(df1)
print(df1.pivot(index='sport',columns='students', values='marks'))
After pivoting
OUTPUT
Filling NA values
import pandas as pd
d1={'students':['Arun','Neha','Supreet','Usha','Mukesh'],'marks':
[78.5,83.4,65.6,92.2,88.6], 'sport':
['Cricket','Badminton','Football','Atheletics','Kabaddi']}
df1=pd.DataFrame(d1)
print(df1)
print(df1.pivot(index='sport',columns='students', values='marks').fillna(10))
OUTPUT:
students Arun Mukesh Neha Supreet Usha
sport
Atheletics 10.0 10.0 10.0 10.0 92.2
Badminton 10.0 10.0 83.4 10.0 10.0
Cricket 78.5 10.0 10.0 10.0 10.0
Football 10.0 10.0 10.0 65.6 10.0
Kabaddi 10.0 88.6 10.0 10.0 10.0