重塑融化的 pandas 数据框 [英] Reshaping a melted pandas dataframe

查看:56
本文介绍了重塑融化的 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从另一个重塑融化的数据框问题.截至目前,这就是我所拥有的:

I'm trying to reshape a melted dataframe from another question. As of now, this is what I have:

    col1  variable  value
0    A     col2      1
1    B     col2      2
2    A     col2      3
3    B     col2      3
4    A     col3      5
5    B     col3      4
6    A     col3      6
7    B     col3      5

我正在尝试将其添加到类似这样的地方:

I'm trying to get it to something like:

  col1 variable value1 value2
0    A     col2   1    3
1    A     col3   5    6 
2    B     col2   2    3
3    B     col3   4    5

要了解这种重新排序背后的逻辑,以下是原始数据帧的样子:

To understand the logic behind this reordering, this is what the original dataframe looks like, sorted:

  col1 variable  value
0    A     col2      1 \   1 (value1 = 1, value2 = 3)
2    A     col2      3 /
4    A     col3      5 \   2 (value1 = 5, value2 = 6)
6    A     col3      6 /
1    B     col2      2 \   3 (value1 = 2, value2 = 3)
3    B     col2      3 /
5    B     col3      4 \   4 (value1 = 4, value2 = 5)
7    B     col3      5 /

我想做的就是重塑.

我相信这与pivotpivot_table有关,但是我不确定...我将如何做?

I believe this would have something to do with pivot or pivot_table, but I'm not sure... How would I do this?

推荐答案

使用groupby

In [589]: (df.groupby(['col1', 'variable']).value.apply(list)
             .apply(pd.Series)
             .rename(columns=lambda x: 'value{}'.format(x+1))
             .reset_index())
Out[589]:
  col1 variable  value1  value2
0    A     col2       1       3
1    A     col3       5       6
2    B     col2       2       3
3    B     col3       4       5

这篇关于重塑融化的 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆