【问题标题】:Use regex to split a list in a pandas row based on single quotes使用正则表达式根据单引号拆分熊猫行中的列表
【发布时间】:2021-04-22 14:07:23
【问题描述】:

我在 pandas 数据框中有一列,其中包含一个字符串列表。每个字符串用逗号分隔。

一行中的列表如下所示:

list = ['banana bread is yummy', 'i hate to have some more bread, can't we eat apples?', 'apples are not good for you, they make you hungry']

我一直在尝试根据正则表达式在列的每一行中拆分列表以获得以下输出:

banana bread is yummy
i hate to have some more bread, can't we eat apples?
apples are not good for you, they make you hungry

但是当我使用时

s = df.assign(conversation=df['conversation'].str.split(',')).explode('conversation')

整个列表用逗号分隔,无论它们是否在同一个字符串中。给我这个输出:

banana bread is yummy
i hate to have some more bread
can't we eat apples?
apples are not good for you 
they make you hungry

关于如何使用正则表达式的任何建议?我尝试了几件事,但得到的结果非常随机。

编辑:

我尝试的另一种方法是:

df['conversation'] = df['conversation'].str.strip('[]')

我首先从每一行中删除方括号,然后拆分所有内容。虽然这种方法有效,但它给我留下了随机的空行。

【问题讨论】:

  • 检查索引~如果索引相同,它们之前的字符串是相同的~
  • @BENY 抱歉,我不太明白。你能给我解释一下吗?

标签: python python-3.x regex pandas


【解决方案1】:

根据here 的回复,我只能回答我自己的问题 :-)

s = df.assign(conversation =df['conversation'].str.split(",(?=(?:[^\']*\'[^\']*\')*[^\']*$)")).explode('conversation')

【讨论】:

    猜你喜欢
    • 2021-07-09
    • 2021-06-11
    • 2020-11-14
    • 2019-10-19
    • 2018-10-07
    • 1970-01-01
    • 2020-08-07
    • 2019-12-20
    • 2018-04-30
    相关资源
    最近更新 更多