Python - Pandas - 导入 Excel 文件,遍历每一行,添加新值,并添加到数据框

标签 python excel pandas loops import-from-excel

我有一个 Excel 文件,其中包含需要导入的项目代码和摘要字段,因此我可以在摘要上运行一个简单的文本摘要器,然后添加到数据框中。

我的 Excel 数据集如下所示:

[Proj_Number] | [Abstract]

JJF-123          | Diabetes is a serious chronic condition.  
JFR-223          | Cardiovascular disease is also a chronic condition. 
JF3-334          | Don't forget about asthma and how much it sucks. 

一旦我导入数据,我想应用我的文本摘要器并得到这个:
[Proj_Number] | [Abstract]                        [Ab_keywords]

JJF-123       | Diabetes is a chronic condition.  |Diabetes, chronic condition                                                                 
JFR-223       | COPD is a also chronic condition. | COPD, chronic condition
JF3-334       | Don't forget about asthma too.    | asthma, forgot

我知道我的代码是错误的,但我只是不知道如何遍历每一行,从摘要中获取摘要关键字,将其添加到数据框中,然后将其导出。

from gensim.summarization.summarizer import summarize
from gensim.summarization import keywords
import pandas as pd

dataset = pd.read_excel('abstracts.xlsx',encoding="ISO-8859-1")
df = pd.DataFrame(dataset)
cols = [1,2]
df = df[df.columns[cols]]

for d in df:
d =  keywords(d, ratio=0.15, split=True))
print(d)

最佳答案

您不想使用 for d in df: 遍历 df 中的每一行

Pandas 有一种方法可以将函数应用于数据帧的每一行并通过 apply 返回一个系列。功能

如果您适本地重命名数据框的列,
df['Ab_keywords'] = df['Abstract'].apply(lambda text: keywords(text, ratio=0.15, split=True))
应该管用。

这里将 lambda 函数应用于 df['Abstract'] 的每一行。并被赋予每行的值作为其参数。

关于Python - Pandas - 导入 Excel 文件,遍历每一行,添加新值,并添加到数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56503058/

相关文章:

python - 如何通过计划执行合并两个程序

python - 在 Python DataFrame 中拆分字符串

python - 使用 NumPy 将二进制数据读取为 BGRA 图像

python - 如何获得实时期权链?

python - 为什么Python不识别字符串类型的格式函数?

python - 并行组装 Numpy 数组

vba - 如何在excel宏中检查activecell是否为A1?

python - 根据fuzzywuzzy比率返回对应行

vba - 使用定义字符串的 Find VBA 函数

excel - 谷歌表格替代回车