我有一个Pandas 数据框,想要将4列堆叠到2列.所以我有这个

df = pd.DataFrame({'date':['2023-12-01', '2023-12-05', '2023-12-07'],
'other_col':['a', 'b', 'c'],
'right_count':[4,7,9], 'right_sum':[2,3,5],
'left_count':[1,8,5], 'left_sum':[0,8,4]})
    date    other_col  right_count  right_sum   left_count  left_sum
0   2023-12-01  a          4           2           1         0
1   2023-12-05  b          7           3           8         8
2   2023-12-07  c          9           5           5         4

并且想要得到这个

    date    other_col   side    count   sum
0   2023-12-01  a       right   4        2
1   2023-12-05  b       right   7        3
2   2023-12-07  c       right   9        5
3   2023-12-01  a       left    1        0
4   2023-12-05  b       left    8        8
5   2023-12-07  c       left    5        4

推荐答案

您可以使用带有临时MultiIndex的自定义整形:

out = (df
   .set_index(['date', 'other_col'])
   .pipe(lambda x: x.set_axis(x.columns.str.split('_', expand=True), axis=1))
   .rename_axis(columns=['side', None])
   .stack('side').reset_index()
)

melt+pivot:

tmp = df.melt(['date', 'other_col'], var_name='side')
tmp[['side', 'col']] = tmp['side'].str.split('_', n=1, expand=True)

out = (tmp.pivot(index=['date', 'other_col', 'side'],
                 columns='col', values='value')
          .reset_index().rename_axis(columns=None)
      )

输出:

         date other_col   side  count  sum
0  2023-12-01         a   left      1    0
1  2023-12-01         a  right      4    2
2  2023-12-05         b   left      8    8
3  2023-12-05         b  right      7    3
4  2023-12-07         c   left      5    4
5  2023-12-07         c  right      9    5

或者,使用janitor库和pivot_longer库要容易得多:

# pip install pyjanitor
import janitor

out = df.pivot_longer(index=['date', 'other_col'],
                      names_to=('side', '.value'),
                      names_pattern=r'([^_]+)_([^_]+)')

输出:

         date other_col   side  count  sum
0  2023-12-01         a  right      4    2
1  2023-12-05         b  right      7    3
2  2023-12-07         c  right      9    5
3  2023-12-01         a   left      1    0
4  2023-12-05         b   left      8    8
5  2023-12-07         c   left      5    4

Python相关问答推荐

从流程获取定期更新

查找3D数组中沿一个轴的相同值序列的长度(与行程长度编码相关)

Tokenizer Docker:无法为Tokenizer构建轮子,这是安装pyproject.toml项目所需的

Python在通过Inbox调用时给出不同的响应

Django文件上传不起作用:文件未出现在媒体目录或数据库中

在后台运行的Python函数

如何在telegram 机器人中发送音频?

除了Python之外,可以替代bare?

在两极中实施频率编码

在Windows上启动新Python项目的正确步骤顺序

如何从FDaGrid实例中删除某些函数?

如何在图片中找到这个化学测试条?OpenCV精明边缘检测不会绘制边界框

处理(潜在)不断增长的任务队列的并行/并行方法

如何在Django基于类的视图中有效地使用UTE和RST HTIP方法?

如何将Docker内部运行的mariadb与主机上Docker外部运行的Python脚本连接起来

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

如何使用Python以编程方式判断和检索Angular网站的动态内容?

SQLAlchemy Like ALL ORM analog

部分视图的DataFrame

在单次扫描中创建列表