Python 取消Pivot数据帧并加入pandas

Python 取消Pivot数据帧并加入pandas,python,pandas,dataframe,join,pivot,Python,Pandas,Dataframe,Join,Pivot,我有这个数据框: +-------+-----+---------+ | group | id | value | +-------+-----+---------+ | A | 92 | 123.123 | | A | 105 | 9034 | | A | 999 | 421 | | B | 92 | 32019 | | B | 105 | 3281 | +-------+-----+---------+ 我希望以“组

我有这个数据框:

+-------+-----+---------+
| group | id  |  value  |
+-------+-----+---------+
| A     |  92 | 123.123 |
| A     | 105 |    9034 |
| A     | 999 |     421 |
| B     |  92 |   32019 |
| B     | 105 |    3281 |
+-------+-----+---------+
我希望以“组”列为轴心,使其值成为“值”列名称的一部分,观察值由“id”连接,如下所示:

+-----+---------+---------+
| id  | A_value | B_value |
+-----+---------+---------+
|  92 | 123.123 | 32019   |
| 105 |    9034 | 3281    |
| 999 |     421 | nan     |
+-----+---------+---------+

执行此操作的最佳方法是什么?

使用
设置索引
取消堆叠
并展平多索引:

df_out = df.set_index(['id','group']).unstack()
df_out.columns = df_out.columns.map('{0[1]}_{0[0]}'.format)
df_out = df_out.reset_index()
print(df_out)
输出:

    id      A_value      B_value
0   92      123.123      32019.0
1  105     9034.000       3281.0
2  999      421.000          NaN

使用
pivot
add_suffix
(通过@ScottBoston)和
reset_index

df.pivot(index = 'id',columns = 'group',values = 'value')\
       .add_suffix('_value')\
       .reset_index()
group     id   A_value  B_value
0       92.0   123.123  32019.0
1      105.0  9034.000   3281.0
2      999.0   421.000      NaN

查看使用
添加后缀(“u值”)
之前的
重置索引
@ScottBoston updated。谢谢add_suffix向所有列添加字符串是否正确?如果原始数据帧中还有另一个值列,您将如何执行此操作?@jerbear您可以使用此:
。重命名({'A':'A_值','B':'B_值'},axis=1)