Python&Pandas:向新列追加数据

2024-10-02 00:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python和Pandas,我正在编写一个脚本,将csv中的文本数据通过pylanguagetool库传递,以计算文本中的语法错误数。脚本成功运行,但将数据附加到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

需要进行哪些更改才能像这样附加输出


Tags: csvthe数据textfrom文本import脚本
2条回答
<>而不是使用循环,您可以考虑^ {CD1>},它将在一行中实现您想要的:

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

Edit:

您可以使用以下命令将上述内容写入.csv文件:

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

您不希望使用mode="a"作为在追加模式下打开文件的方式,而希望使用(默认)写入模式

我的策略是将错误计数保留在一个列表中,然后在原始数据库中创建一个单独的列,最后将该数据库写入csv:

text_data = df["text"].fillna('')
length1 = len(text_data)
error_count_lst = []
for i, x in enumerate(range(length1)):
    errors = api.check(text_data, api_url='https://languagetool.org/api/v2/', lang='en-US')
    result = str(errors)
    error_count = result.count("message")
    error_count_lst.append(error_count)

text_data['error_count'] = error_count_lst
text_data.to_csv('file.csv', index=False)

相关问题 更多 >

    热门问题