使用pyjanitor.pivot_longer拆分多前缀列时的type列填充问题
解决pandas逆透视时提取前缀生成type列的问题
示例数据
col,ref_number_of_rows,ref_count,ref_unique,cur_number_of_rows,cur_count,cur_unique region,2518,2518,42,212,212,12 country,2518,2518,6,212,212,2 year,2518,2518,15,212,212,15
注:原数据最后一列疑似笔误,修正为cur_unique以匹配对应数值逻辑
需求说明
将上述数据集逆透视,生成type列存储列名前缀(cur或ref)。
原代码问题
当前代码无法正确提取下划线前缀填充type列,原因是names_sep参数使用错误——该参数用于指定列名的分隔符,而你传入的正则表达式是匹配前缀内容,无法实现分割效果。
正确解决方案
方法1:按第一个下划线分割(最简方案)
通过names_split="first"指定仅分割第一个下划线,直接将前缀存入type列:
column_summary_frame \ .pivot_longer( column_names="*_*", # 匹配所有含下划线的列 names_to=("type", ".value"), names_sep="_", names_split="first" )
方法2:正则分组精确匹配
如果需要限定仅匹配ref或cur前缀,使用names_pattern捕获分组:
column_summary_frame \ .pivot_longer( column_names="*_*", names_to=("type", ".value"), names_pattern=r"(ref|cur)_(.*)" # 分别捕获前缀和字段名 )
处理后结果示例
| col | type | number_of_rows | count | unique |
|---|---|---|---|---|
| region | ref | 2518 | 2518 | 42 |
| region | cur | 212 | 212 | 12 |
| country | ref | 2518 | 2518 | 6 |
| country | cur | 212 | 212 | 2 |
| year | ref | 2518 | 2518 | 15 |
| year | cur | 212 | 212 | 15 |
内容的提问来源于stack exchange,提问作者prayner
相关产品推荐
相关产品推荐

