[英]Pandas convert dataframe values to column names
我想將數據幀值用作列名並簡化數據幀。
我嘗試了df.stack()
然后是index.map('{0[0]}_{0[1]}'.format)
Input_df(通過執行groupby獲得此df):
link price date
A 1 01/01
A 2 01/02
A 1.2 01/03
Desired_ouput:
link price_01/01 price_01/02 price_01/03
A 1 2 1.2
df.set_index(['link', 'date']).price.unstack().add_prefix('price_')
date price_01/01 price_01/02 price_01/03
link
A 1.0 2.0 1.2
你可以試試這個使用set_index
和unstack
,然后使用Python 3.6或更高版本,您可以使用F-字符串列表理解扁平化多指標列標題。
df_out = df.set_index(['link', 'date']).unstack()
df_out.columns = [f'{i}_{j}' for i, j in df_out.columns]
df_out.reset_index()
輸出:
link price_01/01 price_01/02 price_01/03
0 A 1.0 2.0 1.2
你可以pivot
你的桌子:
df['date'] = 'price_' + df['date']
df.reset_index(inplace=True)
df = df.pivot(index='link', columns='date', values='price')
print(df)
輸出:
date price_01/01 price_01/02 price_01/03
link
A 1.0 2.0 1.2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.