Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何根据特定格式取消列的堆叠?_Python_Pandas - Fatal编程技术网

Python 如何根据特定格式取消列的堆叠?

Python 如何根据特定格式取消列的堆叠?,python,pandas,Python,Pandas,Mydf有一列unnamed,其第一个元素为 '{company=*, location=world, industry=*, segment=*, feature=*, product=*, basekpi=customer_demand}' 第二个元素是NaN。我想将此列拆分为7列公司,位置,行业,细分,功能,产品,以及基本KPI。我的预期的\u df为 你能详细说明一下怎么做吗 import pandas as pd unnamed = ['{company=*, location=w

My
df
有一列
unnamed
,其第一个元素为

'{company=*, location=world, industry=*, segment=*, feature=*, product=*, basekpi=customer_demand}'
第二个元素是
NaN
。我想将此列拆分为7列
公司
位置
行业
细分
功能
产品
,以及
基本KPI
。我的
预期的\u 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

可以替换不需要的字符串并拆分、分解然后取消堆叠:

s = (df['unnamed'].replace({"=":":","{":"","}":""},regex=True)
     .str.split(",").explode().str.split(":"))
u = pd.DataFrame(s.tolist(),s.index).set_index(0,append=True)[1].unstack()
out = df.join(u)


可以替换不需要的字符串并拆分、分解然后取消堆叠:

s = (df['unnamed'].replace({"=":":","{":"","}":""},regex=True)
     .str.split(",").explode().str.split(":"))
u = pd.DataFrame(s.tolist(),s.index).set_index(0,append=True)[1].unstack()
out = df.join(u)

我们可以将
findall
与regex捕获组一起使用,从
unnamed
列中提取键值对

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

正则表达式详细信息

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

我们可以将
findall
与regex捕获组一起使用,从
unnamed
列中提取键值对

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

正则表达式详细信息

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