首页 > 解决方案 > python - 如何在Python pandas中将一列中包含多个句子的文本拆分为多行?

问题描述

我正在尝试将评论列拆分为包含每个句子的多行。我使用以下 StackOverflow 线程作为参考,因为它往往会给出类似的结果。 参考链接: pandas:如何将一列中的文本拆分为多行? 数据框的示例数据如下。

Id Team Food_Text 1 X 食物很好。它煮得很好。可口的!2 十一讨厌鱿鱼。食物煮得不好。确实如此。3 X 请不要在这里任何时候好 4 Y 我喜欢鱼。令人敬畏的美味。5 Y 适合甜点。肉味道不好

'Food_Text' 的每条记录可以是由句号或句点分隔的多个句子。我使用了以下代码

import numpy as np
import pandas as pd

survey_data = pd.read_csv("Food_Dummy.csv")
survey_text = survey_data[['Id','Team','Food_Text']]

# Getting s as pandas series which has split on full stop and new sentence a new line         
s = survey_text["Food_Text"].str.split('.').apply(pd.Series,1).stack()
s.index = s.index.droplevel(-1) # to line up with df's index
s.name = 'Food_Text' # needs a name to join

# There are blank or emplty cell values after above process. Removing them
s.replace('', np.nan, inplace=True)
s.dropna(inplace=True)
x=s.to_frame(name='Food_Text1')
x.head(10)

# Joining should ideally get me proper output. But I am getting original dataframe instead of split one.
survey_text.join(x)
survey_text.head(10)

我不确定为什么连接没有给我一个包含更多行数的正确数据框。根据拆分索引重复其他列。所以 Id=1 有 3 个句子,所以我们应该有 3 个记录,所有其他数据都相同,Food_Text 列有一个来自 ID=1 评论的新句子。其他记录也是如此。

预先感谢您的帮助!问候, 索希尔沙阿

标签: pythonpandastext-miningsentence-synthesis

解决方案


在您放入代码的示例中,join打印了结果,因此如果您想更改您的survey_text 的值,代码应为:

survey_text = survey_text.join(x)

或者如果您想简化代码,下面的代码就可以了:

import numpy as np
import pandas as pd

survey_data = pd.read_csv("Food_Dummy.csv")
survey_text = survey_data[['Id','Team','Food_Text']]

# Getting s as pandas series which has split on full stop and new sentence a new line
s = survey_text["Food_Text"].str.split('.').apply(pd.Series,1).stack()
s.index = s.index.droplevel(-1) # to line up with df's index
s.name = 'Food_Text' # needs a name to join

# There are blank or emplty cell values after above process. Removing them
s.replace('', np.nan, inplace=True)
s.dropna(inplace=True)

# Joining should ideally get me proper output. But I am getting original dataframe instead of split one.
del survey_text['Food_Text']
survey_text = survey_text.join(s)
survey_text.head(10)

这样,您的 DataFrame 中将不会有多个“Food_Text”列。


推荐阅读