You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PyJanitor的pivot_longer同时转换多组带共同前缀的列

用PyJanitor一次性实现多前缀列的长表转换

你需要把带first/second/third前缀的rating/estimate/type列一次性转成包含id、category、rating、estimate、type的长表结构,无需多次调用pivot_longer再合并。

原始数据集

import pandas as pd
import janitor

df = pd.DataFrame({
    'id': [1, 1, 1],
    'first_rating': [1, 2, 3],
    'second_rating': [2.8, 2.9, 2.2],
    'third_rating': [3.4, 3.8, 2.9],
    'first_estimate': [1.2, 2.4, 2.8],
    'second_estimate': [2.4, 3, 2.4],
    'third_estimate':[3.4, 3.8, 2.9],
    'first_type': ['red', 'green', 'blue'],
    'second_type': ['red', 'green', 'yellow'],
    'third_type': ['red', 'red', 'blue'],
})

问题分析

你之前多次调用pivot_longer的方式会重复生成category列,导致数据行数爆炸且结构混乱,完全没必要。PyJanitor的pivot_longer支持多列分组拆分,用正则匹配列名的前缀和后缀就能一次性搞定。

高效解决方案

核心是利用names_pattern正则捕获列名里的前缀(category)和后缀(指标类型),再通过names_to里的.value关键字自动映射对应列:

result = df.pivot_longer(
    column_names=df.columns.drop('id'),  # 选择所有非id列
    names_pattern=r'(.*)_(.*)',  # 正则拆分:前缀(如first)和后缀(如rating)
    names_to=['category', '.value']  # .value表示把后缀作为新列名
)

print(result)

输出结果

id category  rating  estimate   type
0   1    first     1.0       1.2    red
1   1    first     2.0       2.4  green
2   1    first     3.0       2.8   blue
3   1   second     2.8       2.4    red
4   1   second     2.9       3.0  green
5   1   second     2.2       2.4 yellow
6   1    third     3.4       3.4    red
7   1    third     3.8       3.8    red
8   1    third     2.9       2.9   blue

参数解释

  • column_names:指定要转换的列,这里排除id列
  • names_pattern=r'(.*)_(.*)':正则表达式,把列名拆成两部分,第一部分是first/second/third(对应category),第二部分是rating/estimate/type(对应新列的名称)
  • names_to=['category', '.value']:category用来存前缀,.value是特殊关键字,告诉PyJanitor把后缀作为新的列名,自动匹配对应的值

这样就一次性完成了所有列的长表转换,效率高且结构正确。

内容的提问来源于stack exchange,提问作者prayner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 22:25:19