首页 > 解决方案 > 如何从 pandas.DataFrame 中的段落中提取句子并保留段落键?

问题描述

我有一个pandas.DataFrame1604 段如下:

在此处输入图像描述

我想提取所有句子(即使是使用点的幼稚方式)并提供一个新的数据框,该数据框在每一行中都有一个句子和前一列的值,尤其是段落键(主要是左侧第一列中的索引)

我已经对此进行了研究,并且可以为每个句子提供章节列,如下所示:

 # Create lists to fill with values
l_col1 = []
l_col2 = []

# iterate over each row and fill our lists
for ix, row in dfAstroNova.iterrows():
    for value in row['sentences']:
        l_col1.append(value)
        l_col2.append(row['chapter'])

# Create new dataframe from the two lists
df= pd.DataFrame({'sentences': l_col1 ,
                         'chapter': l_col2 })
df=df.rename(columns={"sentences":"sents"});

这给了我这个数据框(dfAstroNova 是原始数据框的名称)

如您所见,我有章节键。我的问题是如何添加段落键(即主数据框中的列文本数到新数据框)

然后我有另一列显示该句子属于原始数据框中的哪个段落,或者更好的是一个附加列,其中每个句子都包含相应的段落?

在此处输入图像描述

标签: pandasstringnlptext-classification

解决方案


我已经这样做了

 # Create lists to fill with values
l_col1 = []
l_col2 = []
l_col3 = []

# iterate over each row and fill our lists
for ix, row in dfAstroNova.iterrows():
    for value in row['sentences']:
        l_col1.append(value)
        l_col2.append(row['chapter'])
        l_col3.append(row['text'])

# Create new dataframe from the two lists
df= pd.DataFrame({'sentences': l_col1 ,
                         'chapter': l_col2 , 'paragraph': l_col3})
df=df.rename(columns={"sentences":"sents"});

这是结果:

在此处输入图像描述

现在,我只需要为段落定义一个键并将其添加到新表中!


推荐阅读