【发布时间】: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