首页 > 解决方案 > Python & Pandas:将数据附加到新列

问题描述

使用 Python 和 Pandas,我正在编写一个脚本,通过 pylanguagetool 库从 csv 传递文本数据,以计算文本中的语法错误数量。该脚本成功运行,但将数据附加到 csv 的末尾而不是新列。

csv的结构是:

CSV1

工作代码是:

import pandas as pd
from pylanguagetool import api

df = pd.read_csv("Streamlit\stack.csv")

text_data = df["text"].fillna('')
length1 = len(text_data)

for i, x in enumerate(range(length1)):
    # this is the pylanguagetool operation
    errors = api.check(text_data, api_url='https://languagetool.org/api/v2/', lang='en-US')
    result = str(errors)
    # this pulls the error count "message" from the pylanguagetool json
    error_count = result.count("message")
    output_df = pd.DataFrame({"error_count": [error_count]})
    output_df.to_csv("Streamlit\stack.csv", mode="a", header=(i == 0), index=False)

输出是:

CSV2

预期输出:

CSV3

附加这样的输出需要进行哪些更改?

标签: pythonpandas

解决方案


lambda您可能会考虑使用哪一行来完成您想要的,而不是使用循环:

df["error_count"] = df["text"].fillna("").apply(lambda x: len(api.check(x, api_url='https://languagetool.org/api/v2/', lang='en-US')["matches"]))

>>> df
   user_id  ... error_count
0       10  ...           2
1       11  ...           0
2       12  ...           0
3       13  ...           0
4       14  ...           0
5       15  ...           2

编辑:

您可以将上述内容写入 .csv 文件:

df.to_csv("Streamlit\stack.csv", index=False)

您不想使用它以附加mode="a"模式打开文件,而您想要(默认)写入模式。


推荐阅读