[英]Pandas convert dataframe values to column names
I want to use dataframe values as column names and simplify the dataframe. 我想将数据帧值用作列名并简化数据帧。
I tried df.stack()
and then index.map('{0[0]}_{0[1]}'.format)
我尝试了
df.stack()
然后是index.map('{0[0]}_{0[1]}'.format)
Input_df(Got this df by doing a groupby): Input_df(通过执行groupby获得此df):
link price date
A 1 01/01
A 2 01/02
A 1.2 01/03
Desired_ouput: 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
You can try this using set_index
and unstack
, then using Python 3.6+ can you use f-string with list comprehension to flatten multiindex column headers. 你可以试试这个使用
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()
Output: 输出:
link price_01/01 price_01/02 price_01/03
0 A 1.0 2.0 1.2
You can pivot
your table: 你可以
pivot
你的桌子:
df['date'] = 'price_' + df['date']
df.reset_index(inplace=True)
df = df.pivot(index='link', columns='date', values='price')
print(df)
Output: 输出:
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.