数据透视表和堆叠操作
数据透视表
pd.pivot_table(df, values='D', index=['A','B'], columns=['C'], aggfunc=np.sum)
pd.pivot_table(df.set_index(['datetime']).loc['20220201':'20220202'], values='num', index=['name'], columns=['datetime']).assign(ratio=lambda x: (x['20220202'] - x['20220201']) / x['20220201'])
pd.pivot_table(df.set_index(['datetime']).loc['20220201':'20220215'].to_Period('W'), values='num', index=['name'], columns=['datetime'], aggfunc=np.sum).assign(ratio=lambda x: (x.to_period('w').loc[pd.to_datetime('2022-01-31/2022-02-06')] - x.to_period('w').loc[pd.to_datetime('2022-02-07/2022-02-13')] ) / x.to_period('w').loc[pd.to_datetime('2022-02-07/2022-02-13')] )
堆叠
stacked = df.stack()
stacked = df.stack('exp')
stacked = df.stack(0)
stacked = df.stack(-1)
stacked = df.stack([0,1])
stacked.unstack()
df = pd.DataFrame(np.array([[1,2,3],[2,3,4]]), columns=['col1','col2','col3'])
df1 = df.set_index(['col1','col2']).unstack()
df1.columns
>>> MultiIndex([('col3', 2),
('col3', 3)],
names=[None, 'col2'])
df2 = pd.pivot_table(df,values='col3',columns=['col2'],index=['col1'])
df2.columns
>>> Int64Index([2, 3], dtype='int64', name='col2')
stacked.unstack(1)
stacked.unstack(0)
stacked = df.melt(id_vars=['first', 'last'],var_name='存放变量的列名', value_name='存放值的列名')
独热编码
pd.get_dumies(df['key'])
列转行
df['values'].explode()
df.explode('values')