Pivot table in Python
create a pandas dataframe-
import numpy as np
import pandas as pd
cars_data= pd.DataFrame([[10,5,3,'X'], [1,2,3,'Y'],[3,4,5,'X'], [10,5,3,'X'], [1,2,3,'Y'],[3,4,5,'X']], columns=['A','B','C','Type'])
cars_data
create pivot_table a method in pandas
# using pivot to convert rows to column
pivot_car= cars_data.pivot_table(columns=['Type', 'A'], aggfunc= [np.mean, np.amax])
import numpy as np
import pandas as pd
cars_data= pd.DataFrame([[10,5,3,'X'], [1,2,3,'Y'],[3,4,5,'X'], [10,5,3,'X'], [1,2,3,'Y'],[3,4,5,'X']], columns=['A','B','C','Type'])
cars_data
A | B | C | Type | |
---|---|---|---|---|
0 | 10 | 5 | 3 | X |
1 | 1 | 2 | 3 | Y |
2 | 3 | 4 | 5 | X |
3 | 10 | 5 | 3 | X |
4 | 1 | 2 | 3 | Y |
5 | 3 | 4 | 5 | X |
create pivot_table a method in pandas
# using pivot to convert rows to column
pivot_car= cars_data.pivot_table(columns=['Type', 'A'], aggfunc= [np.mean, np.amax])
mean | amax | |||
---|---|---|---|---|
Type | A | |||
B | X | 3 | 4 | 4 |
10 | 5 | 5 | ||
Y | 1 | 2 | 2 | |
C | X | 3 | 5 | 5 |
10 | 3 | 3 | ||
Y | 1 | 3 | 3 |
Comments
Post a Comment