gpt4 book ai didi

python Pandas : extract data from a cell and turn it into a column

转载 作者:行者123 更新时间:2023-12-01 23:22:42 25 4
gpt4 key购买 nike

我有一个带有这种模式的有点困惑的数据集:

ID       Value
abc (john:10),(albert:5),(hanna:7) ...
def (frank:5),(dave:8),(ben:11) ...

我当然更愿意使用这种格式的数据:

ID       Value1  Value2
abc john 10
abc albert 5
abc hanna 7
def frank 5
def dave 8
def ben 11

但是,我对如何做到这一点有些困惑?我能想出的唯一解决方案是循环遍历并将非常新的数据点添加到新的数据框。

是否有更好、更有效的方法?

谢谢!

最佳答案

str.extractall

我们可以从 Value 列中的字符串中提取所有出现的 regex 模式

df.set_index('ID')['Value'].str.extractall(r'\((\w+):(\d+)\)').droplevel(1)

          0   1
ID
abc john 10
abc albert 5
abc hanna 7
def frank 5
def dave 8
def ben 11

正则表达式详细信息:

  • \(:匹配字符(字面上的
  • (\w+) :第一个捕获组
    • \w+ :匹配一个或多个单词字符
  • : : 匹配字符 : literally
  • (\d+) :第二个捕获组
    • \d+ :匹配一个或多个数字
  • \) :匹配字符 ) 字面意思

在线查看regex demo

关于 python Pandas : extract data from a cell and turn it into a column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67758485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com