python - 如何根据某种格式取消堆叠熊猫列?
问题描述
我df
的列unnamed
的第一个元素是
'{company=*, location=world, industry=*, segment=*, feature=*, product=*, basekpi=customer_demand}'
第二个元素是NaN
。我想将此列拆分为 7 列company
、location
、industry
、segment
、feature
、product
和basekpi
。我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
解决方案
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
推荐阅读
- clr-profiling-api - 如何使用 ICorProfilerInfo3 接口中的 GetFunctionEnter3Info 函数从 COR_PRF_ELT_INFO 获取 COR_PRF_FUNCTION_ARGUMENT_INFO
- python - django中的切片与查询集
- php - 在 Laravel 中提交帖子 - 找不到两分钟的数字
- c# - HTML 敏捷包 HtmlNode.InnerText 不工作/不一致的行为
- r - 使用 R 的带有 httr 包的 POST 请求
- mysql - 为什么 MYSQL Sleep(x) 会一直持续下去?
- java - 对话框按钮的可视化定制
- matlab - 不同数据类型的相同矩阵的空空间计算不一致
- python - 如何打印可用的桶?
- python - ActionChains 不会在 Chrome webdriver 实现中调用 reset_actions() 上的 keyUp 事件