python - 使用 to_csv 循环仅打印最后一个文件(Python)
问题描述
我正在尝试从一个文件夹中加载多个 csv 文件,使用一个计算每个文件的缺失值的函数,然后保存包含输出的新 csv 文件。当我编辑脚本以打印输出时,我得到了预期的结果。但是,循环只会将最后一个文件保存到目录中。我正在使用的代码是:
from pathlib import Path
import pandas as pd
import os
import glob
files = glob("C:/Users/61437/Desktop/test_folder/*.csv") # get all csv's from folder
n = 0
for file in files:
print(file)
df = pd.read_csv(file, index_col = False)
d = calc_missing_prices(df) # calc_missing_prices is a user defined function
print(d)
d.to_csv(r'C:\Users\61437\Desktop\test_folder\derived_files\derived_{}.csv'.format(n+1), index = False)
print() 命令返回预期的输出,我的数据是:
C:/Users/61437/Desktop/test_folder\file1.csv
V_150 V_200 V_300 V_375 V_500 V_750 V_1000
0 3.00 2.75 4.50 6.03 8.35 12.07 15.00
1 2.32 3.09 4.63 5.00 9.75 12.50 12.25
2 1.85 2.47 3.70 4.62 6.17 9.25 12.33
3 1.75 2.00 4.06 6.50 6.78 10.16 15.20
C:/Users/61437/Desktop/test_folder\file2.csv
V_300 V_375 V_500 V_750 V_1000
0 4.00 4.50 6.06 9.08 11.00
1 3.77 5.00 6.50 8.50 12.56
2 3.00 3.66 4.88 7.31 9.50
C:/Users/61437/Desktop/test_folder\file3.csv
V_500 V_750 V_1000
0 5.50 8.25 11.00
1 6.50 8.50 12.17
2 4.75 7.12 9.50
但是,唯一保存的 csv 文件是“derived_1.csv”,其中包含 file3.csv 的输出
我在做什么阻止创建所有三个文件?
解决方案
您没有n
在循环内递增。您的数据存储在文件derived_1.csv
中,每次迭代都会覆盖该文件。一旦for
循环完成执行,只会保存最后一个 csv。
n += 1
在for
循环中包含该行以在每次迭代时将其递增 1。
推荐阅读
- node.js - 尽管有 babel,但箭头功能不起作用
- google-api - gmail的批处理api如何用于列出gmail?
- angular - Angular:使用来自另一个组件的服务构建问题
- git - 使用 HTTP URL 克隆存储库
- c# - 用 && 里面 if 检查多个相似的条件
- css - Css 对齐材料设计单选按钮
- python - 使用 python 创建示例 XML 文件
- javascript - fetch() 和 window.fetch() 有什么区别?
- reactjs - 只有在 API 响应在 redux 的 props 中可用后,我才能更改状态?
- jenkins - 如何从 Bitbucket Cloud 触发多分支作业?