xxxxxxxxxx
df.pivot_table(['int_age'],index = [df.iloc[:,meet_friends], df.iloc[:,friendsgiving]])
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
>>df.pivot(index='foo', columns='bar', values=['baz', 'zoo'])
bar A B C
foo
one 1 2 3
two 4 5 6
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
import pandas as pd
# Sample DataFrame (long-format data)
data = {
'Date': ['2023-01-01', '2023-01-01', '2023-01-02', '2023-01-02'],
'Category': ['A', 'B', 'A', 'B'],
'Value': [10, 15, 12, 18]
}
df = pd.DataFrame(data)
# Using pivot to reshape the data
pivot_df = df.pivot(index='Date', columns='Category', values='Value')
print(pivot_df)
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
df.pivot_table(values, index, aggfunc={'value_1': np.mean,'value_2': [min, max, np.mean]})