首页 > 解决方案 > 如何根据某种格式取消堆叠熊猫列?

问题描述

df的列unnamed的第一个元素是

'{company=*, location=world, industry=*, segment=*, feature=*, product=*, basekpi=customer_demand}'

第二个元素是NaN。我想将此列拆分为 7 列companylocationindustrysegmentfeatureproductbasekpi。我expected_df的是

在此处输入图像描述

您能否详细说明如何执行此操作?

import pandas as pd
unnamed = ['{company=*, location=world, industry=*, segment=*, feature=*, product=*, basekpi=customer_demand}',
           'NaN']
df = pd.DataFrame({'id': [0, 1], 'unnamed': unnamed})
df

标签: pythonpandas

解决方案


Series.str.findall

我们可以使用正则表达式捕获组从列findall中提取键值对unnamed

pd.DataFrame(map(dict, df['unnamed'].str.findall(r'([^{=,]+)=([^,}]+)')))

  company  location  industry  segment  feature  product          basekpi
0       *     world         *        *        *        *  customer_demand
1     NaN       NaN       NaN      NaN      NaN      NaN              NaN

正则表达式详细信息

  • ([^{=,]+): 第一个捕获组
    • [^=,]+:匹配列表中不存在的任何字符[{=,]一次或多次
  • ==:从字面上匹配字符
  • ([^,}]+): 第二个捕获组
    • [^,]+:匹配列表中不存在的任何字符[,}]一次或多次

见网上regex demo


推荐阅读