python - Python & Pandas:将数据附加到新列
问题描述
使用 Python 和 Pandas,我正在编写一个脚本,通过 pylanguagetool 库从 csv 传递文本数据,以计算文本中的语法错误数量。该脚本成功运行,但将数据附加到 csv 的末尾而不是新列。
csv的结构是:
工作代码是:
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)
输出是:
预期输出:
附加这样的输出需要进行哪些更改?
解决方案
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"
模式打开文件,而您想要(默认)写入模式。
推荐阅读
- cassandra - 安装后无法访问 Cassandra NoSQL DB
- python - __init__() 得到了一个意外的关键字参数“book_category”
- java - 让用户在 Java 中放置按钮
- symfony - Symfony Webpack Encore 高级/自定义配置
- python - 你如何用python按住左键?
- go - /var 上的 os.Lstat Mode().IsDir() 方法产生 false
- python - Python smtplib ssl 套接字需要很长时间才能创建
- angular - Angular http 发布并等待多个结果
- node.js - 从导出函数调用普通函数,但返回结果未正确投影
- c++ - 如何处理 vtk 中读取/写入层的精度损失?