python - 在 Python 中使用循环从 CSV 中提取值
问题描述
我正在尝试遍历 CSV 中的行和列(如下所示)
DateTime 762972 763753 763776 769472 793144 799864 812926
01/01/2017 00:00 -1 0.015 -1 0.33 0 0 0.27
01/01/2017 00:15 -1 0.015 -1 0.12 0 0.015 0.06
01/01/2017 00:30 -1 0.015 -1 0.15 0 0 0
01/01/2017 00:45 -1 0.015 -1 0.165 0 0 0.15
01/01/2017 01:00 -1 0.015 -1 0 0 0 0
01/01/2017 01:15 -1 0.015 -1 0 0 0 0.135
生成这样的输出
762972, 01/01/2017 00:00:00, -1
762972, 01/01/2017 00:15:00, -1
762972, 01/01/2017 00:30:00, -1
...
762753, 01/01/2017 00:00:00, 0.015
762753, 01/01/2017 00:15:00, 0.015
762753, 01/01/2017 00:30:00, 0.015
...
769472, 01/01/2017 00:00:00, 0.33
769472, 01/01/2017 00:15:00, 0.12
769472, 01/01/2017 00:30:00, 0.15
所以返回每个时间戳的读数,sensor_id, intersect
我有兴趣了解如何使用 Python 循环/迭代来做到这一点
解决方案
使用Pandas和 chunksize:
import pandas as pd
for df in pd.read_csv('file.csv', chunksize=1):
print(df)
此外,如果文件不是那么大,请考虑将完整的 csv 加载到 pandas DataFrame 中,然后进行迭代:
df = pd.read_csv('file.csv')
for index, row in df.iterrows():
print(index, row)
推荐阅读
- python - 将字符串与“{”符号进行比较的问题
- r - R: Formattable -Column 不会根据条件更新
- angular - 什么时候在 Angular 中使用路由?
- python-3.x - 在连接期间停止 python 请求
- javascript - 为什么 Number 在我的 Teaspoon/Jasmine 规格测试中不是构造函数?
- bash - 如何抽象出 .Net Core 版本号?
- html - 对齐按钮内的项目
- c++ - 尽管安装了驱动程序,Ubuntu 上的 Qt 5.9.5 在“/usr/include/libdrm”中找不到“GL/gl.h”
- azure - 在代码中组合无服务器 Azure 函数但独立运行
- java - 从 ALB 到 20 多个容器的 ECS Fargate 路由