python - 聚合 pandas 列中连续非 NaN 单元格的字符串,但不聚合整个列

标签 python excel pandas text document

我正在解决一个 nlp 问题,我必须分析格式奇怪的 Excel 文件。

有一列包含文本,其中每个文档跨越多个单元格。文档本身由空单元格分隔。我想从文本数据中预测其他列的分数。

This is what it looks like

我已将工作表导入 pandas 数据框,现在我尝试聚合属于每个文档的单元格,同时保留分数。

This is the goal state

我已经开始尝试嵌套循环,但我觉得它比必要的复杂得多。

你会如何处理这个问题?每个文档涵盖不同数量的单元格,并且文档由不同数量的空单元格分隔。为了使其更复杂,右侧列中的分数有时与相应文档的第一个单元格位于同一行,有时与最后一个单元格位于同一行。

非常感谢您的帮助!必须有一个简单的解决方案。

最佳答案

只是一个简单的例子,它是如何工作的:

import pandas as pd
# setting up the DataFrame with sample data
df = pd.DataFrame({'Document': ['This is ', 'first', None, 'This is ', 'second', `None, 'this ', 'is ', 'third'],`
                   'Score': [None, 1, None, None, 2, None, None, 3, None]})

result_df = pd.DataFrame({'Document':[], 'Score':[]})
doc = ''
for index, row in df.iterrows():
    if pd.notnull(row['Score']):
        #any not NaN value within processed document is score 
        score = row['Score']
    if row['Document']:
        #build doc string until the line is not NaN
        doc += row['Document']
    else:
        result_df = result_df.append({'Document':doc, 'Score':score}, ignore_index=True)
        doc = ''

if doc:
    #when the last line (Document) is not NaN save/print results also:
    result_df = result_df.append({'Document':doc, 'Score':score}, ignore_index=True)

输出(result_df):

Document    Score
0   This is first   1.0
1   This is second  2.0
2   This is third   3.0

关于python - 聚合 pandas 列中连续非 NaN 单元格的字符串,但不聚合整个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54110103/

相关文章:

python - 正则表达式并使用 python 替换字符串

php - Windows 上的多个 Web 开发环境

excel - 使用 Excel VBA 搜索并定位列标题

python - 将 numpy 数组更改为数据帧并合并两个数据帧

python - 高阶函数(映射)

python - Python 中的时间旅行调试 - 建议使用哪些工具?

excel - 如何使用 Excel VBA 在多行单元格中的每行最后一个斜杠之后获取单词?

excel - 传递具有从另一个用户定义函数返回的值的数组

python - 更快地向前填充和向后填充 groupby

python - 创建一列并随机赋值