有原始数据格式如下:
需要将type列拆分为按照type值为列,值为monetary值的表,如下:
代码可以写为:
#将原数据的指定列按照列的内容拆分为新的列
def pivot():
table=pd.DataFrame({'cust_id':[10001,10001,10002,10002,10003],
'type':['Normal','Special_offer','Normal','Special_offer','Special_offer'],
'Monetary':[3608,420,1894,3503,4567]})
print(table)
print('-'*60)
table_pivot=table.pivot_table(values='Monetary',index='cust_id',columns='type',fill_value=0,aggfunc='sum')
print(table_pivot)
有原始数据格式如下:
需要将normal和special_offer合并为type列,值为各自值的表,如下:
代码可以写为:
def melt():
table=pd.DataFrame({'cust_id':[10001,10002,10003],
'Normal':[3608,1894,0],
'Special_offer':[420,3503,4567]})
print(table)
print('-'*60)
table_melt=table.melt(id_vars='cust_id',value_vars=['Normal','Special_offer'],value_name='Monetary',var_name='type')
print(table_melt)