首页 > 解决方案 > 在 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 循环/迭代来做到这一点

标签: pythonloops

解决方案


使用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)

推荐阅读