熊猫将数据框值转换为列名

Pas*_*chi 2 python dataframe pandas

我想将数据框值用作列名并简化数据框。

我尝试过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
Run Code Online (Sandbox Code Playgroud)

所需输出:

link price_01/01 price_01/02 price_01/03
  A      1            2         1.2
Run Code Online (Sandbox Code Playgroud)

piR*_*red 6

忘记多索引上的映射

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
Run Code Online (Sandbox Code Playgroud)


Sco*_*ton 5

您可以使用set_index和进行尝试unstack,然后使用Python 3.6 及更高版本,可以将f-string与列表推导一起使用来展平multiindex列标题。

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()
Run Code Online (Sandbox Code Playgroud)

输出:

  link  price_01/01  price_01/02  price_01/03
0    A          1.0          2.0          1.2
Run Code Online (Sandbox Code Playgroud)


Myk*_*tko 5

您可以在pivot您的桌子上:

df['date'] = 'price_' + df['date']
df.reset_index(inplace=True)
df = df.pivot(index='link', columns='date', values='price')

print(df)
Run Code Online (Sandbox Code Playgroud)

输出:

date  price_01/01  price_01/02  price_01/03
link                                       
A             1.0          2.0          1.2
Run Code Online (Sandbox Code Playgroud)