xxxxxxxxxx
df.pivot_table(values, index, aggfunc={'value_1': np.mean,'value_2': [min, max, np.mean]})
xxxxxxxxxx
df.pivot_table(index='cat_col_as_row_number', # multi-level: ['country', 'city']
columns='cat_col_as_columns',
values='num_col_as_values',
fill_value = 0,
margins = True,
aggfunc=[np.mean,np.median]) # axis = "index" / "columns"
# Unpivot a table (wide table format to long table format )
unpivot_df = df.melt(id_vars=['col1_to_keep','col2_to_keep'],
value_vars=['col3_to_unpivot','col4_to_unpivot'],
var_name=['variable_col'], value_name='value_col')
xxxxxxxxxx
table = pd.pivot_table(df, values='D', index=['A', 'B'],
columns=['C'], aggfunc=np.sum)
>>> table
C large small
A B
bar one 4.0 5.0
two 7.0 6.0
foo one 4.0 1.0
two NaN 6.0
xxxxxxxxxx
table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
aggfunc={'D': np.mean,
'E': [min, max, np.mean]})
>>> table
D E
mean max mean min
A C
bar large 5.500000 9 7.500000 6
small 5.500000 9 8.500000 8
foo large 2.000000 5 4.500000 4
small 2.333333 6 4.333333 2
xxxxxxxxxx
>>> emp.pivot_table(index='dept', columns='gender', values='salary', aggfunc='mean').round(-3)
xxxxxxxxxx
df.pivot(index="lev1", columns=["lev2", "lev3"],values="values")
xxxxxxxxxx
table = pd.pivot_table(df, values='D', index=['A', 'B'],
columns=['C'], aggfunc=np.sum, fill_value=0)
xxxxxxxxxx
table = pd.pivot_table(df, values='D', index=['A', 'B'],
columns=['C'], aggfunc=np.sum)
xxxxxxxxxx
>>> df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two',
'two'],
'bar': ['A', 'B', 'C', 'A', 'B', 'C'],
'baz': [1, 2, 3, 4, 5, 6],
'zoo': ['x', 'y', 'z', 'q', 'w', 't']})
>>> df
foo bar baz zoo
0 one A 1 x
1 one B 2 y
2 one C 3 z
3 two A 4 q
4 two B 5 w
5 two C 6 t
>>> df.pivot(index='foo', columns='bar', values='baz')
bar A B C
foo
one 1 2 3
two 4 5 6