python - DataFrame iterrows() 和 .to_csv : Writing row by row

标签 python pandas loops csv

我正在使用以下脚本

  • 将一个函数应用到 DataFrame 的每一行中的列
  • 将该函数的返回值写入 DataFrame 的两个新列
  • 不断将DataFrame写入*.csv

我想了解是否有更好的方法来运行以下计算:

df = 一个 500 行 20 列的 DataFrame

for index, row in df.iterrows():
    df.loc[index, 'words'], df.loc[index, 'count'] = transcribe(df.loc[index, 'text'])
    df.to_csv('out.csv', encoding='utf-8', index=False)

目前,脚本每次(针对每一行)将完整的 df 数据帧输出为 *.csv,包括计算行“words”和“counts”的附加值,直到那时。我想知道,是否也可以逐行完整地写,即只输出 csv 中完整的那些行。

谢谢!

最佳答案

我不明白你为什么要逐行而不是在最后写入整个数据帧,但这里有一个解决你的问题的方法:以追加模式写入数据帧的切片(即当前行) , 只为第一行添加标题:

is_first_row = True
for index, row in df.iterrows():
    df.loc[index, 'words'], df.loc[index, 'count'] = transcribe(df.loc[index, 'text'])
    df.loc[index:index].to_csv('out.csv', encoding='utf-8', index=False, mode='a', header=is_first_row)
    is_first_row = False


根据脚本可能被中断的评论更新:
在这种情况下,您可能希望通过检查文件是否已存在或是否是新文件来确定是否写入 header :

with open('out.csv', encoding='utf-8', mode='a') as f:
    for index, row in df.iterrows():
        df.loc[index, 'words'], df.loc[index, 'count'] = transcribe(df.loc[index, 'text'])
        df.loc[index:index].to_csv(f, index=False, header=f.tell()==0)

关于python - DataFrame iterrows() 和 .to_csv : Writing row by row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57444905/

相关文章:

python - 有没有一种聪明的方法可以将我的脏代码从特定颜色更改为另一种颜色?

python - python pandas 中的季节性数据选择

python - pandas 数据透视表 降序排列 python

php - 同一天两次之间以 15 分钟为增量打印时间

javascript - 循环函数 document.getElementById()

Python - 点类没有得到正确的输出

python - 零钱计算器仅在需要一种硬币时才有效

Python Acme V2 - 重用订单/挑战

python - 获取有序 CSV 文件中高于特定 unix 时间戳的行号的有效方法

javascript - 有没有办法在 HAML 的 :javascript region? 中使用 Ruby 循环