python - 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 评论的新句子。其他记录也是如此。
预先感谢您的帮助!问候, 索希尔沙阿
解决方案
在您放入代码的示例中,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”列。
推荐阅读
- php - 如何修复运行两次的sql代码
- javascript - 如何使用 for 语句和数组确定单击了哪个元素
- xpath - 未从晨星导入数据表
- amazon-web-services - 无服务器框架 - 如何禁用到 AWS Lambda 函数的所有 API 路由并仅使用 SNS
- go - 关机后 Gorilla mux 重用/重新启动服务器
- swift - 从 firestore 分配用户名值
- c - Defining constant in c with const keyword
- javascript - 有没有更漂亮的方法来捕获 JSON 数组块上的错误?
- django-models - 在表“app_job”上插入或更新违反了外键约束“app_job_user_id”详细信息:表“accounts_user”中不存在键(user_id)=(1)
- c - 如何使用具有显式子 pid 的多个 waitpid() 作为特定进程执行顺序的参数