簡體   English   中英

Pandas將數據幀值轉換為列名

[英]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_indexunstack ,然后使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM