第1章 - 从CSV读取数据¶
有几种方法可以从CSV文件中读取数据。以下是最常见的方法:
原生阅读
the CSV模块
the numpy module
the pandas 模块
在本章中,您将学习如何使用pandas读取和过滤CSV数据。 此外,您可以通过命令行选项将数据文件传递给您的脚本。
以下Python脚本,main.py,展示了如何做到这一点:
1from __future__ import annotations
2
3import argparse
4import pandas as pd
5
6
7def read_data(fname):
8 return pd.read_csv(fname)
9
10
11if __name__ == "__main__":
12 options = argparse.ArgumentParser()
13 options.add_argument("-f", "--file", type=str, required=True)
14 args = options.parse_args()
15 data = read_data(args.file)
16 print(data)
17
Python脚本使用argparse模块来接受和解析来自命令行的输入。然后它使用输入,在这种情况下是文件名,来读取并将数据打印到提示符。
尝试以下列方式运行脚本,以检查是否获得所需的输出:
$python datavisualize1/main.py -f all_hour.csv
time latitude longitude depth ... magNst status locationSource magSource
0 2019-01-10T12:11:24.810Z 34.128166 -117.775497 4.46 ... 6.0 automatic ci ci
1 2019-01-10T12:04:26.320Z 19.443333 -155.615997 0.72 ... 6.0 automatic hv hv
2 2019-01-10T11:57:48.980Z 33.322500 -116.393167 4.84 ... 11.0 automatic ci ci
3 2019-01-10T11:52:09.490Z 38.835667 -122.836670 1.28 ... 7.0 automatic nc nc
4 2019-01-10T11:25:44.854Z 65.108200 -149.370100 20.60 ... NaN automatic ak ak
5 2019-01-10T11:25:23.786Z 69.151800 -144.497700 10.40 ... NaN reviewed ak ak
6 2019-01-10T11:16:11.761Z 61.331800 -150.070800 20.10 ... NaN automatic ak ak
[7 rows x 22 columns]