我试图将Comments列分成多行,其中包含每个句子。我使用下面的StackOverflow线程作为参考,因为它倾向于给出类似的结果。 参考链接:pandas: How do I split text in a column into multiple rows? dataframe的示例数据如下。在
Id团队食物 1份食物不错。这道菜做得很好。好吃! 我讨厌鱿鱼。食物煮得不好。确实如此。 请不要在这里任何时候都好 我喜欢鱼。美味无比。 5岁适合做甜点。肉吃起来不好
“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)
我不知道为什么join没有给我一个具有更多行数的正确的数据帧。基于拆分索引重复其他列。所以Id=1有3个句子,所以我们应该有3个记录,所有其他数据都相同,Food_Text列中有一个来自Id=1的注释的新句子。其他记录也是如此。在
提前感谢您的帮助! 当做, 索希尔·沙阿
在您放入代码的示例中,
join
的结果已打印出来,因此如果您想更改调查文本的值,代码应该是:survey_text = survey_text.join(x)
或者,如果您想简化代码,下面的代码就可以了:
这样你就不会在yout数据框中有多个“Food_Text”列。在
相关问题 更多 >
编程相关推荐