用Pythonic方法读取带有行和列标题的CSV

2024-05-17 10:18:28 发布

您现在位置:Python中文网/ 问答频道 /正文

让我们有一个带有行和列标题的CSV表,例如:

, "Car", "Bike", "Boat", "Plane", "Shuttle"
"Red", 1, 7, 3, 0, 0
"Green", 5, 0, 0, 0, 0
"Blue", 1, 1, 4, 0, 1

我想得到行和列标题,即:

col_headers = ["Car", "Bike", "Boat", "Plane", "Shuttle"]
row_headers = ["Red", "Green", "Blue"]
data = [[1, 7, 3, 0, 0],
        [5, 0, 0, 0, 0],
        [1, 1, 4, 0, 1]]

我当然可以做些

import csv
with open("path/to/file.csv", "r") as f:
    csvraw = list(csv.reader(f))
col_headers = csvraw[1][1:]
row_headers = [row[0] for row in csvraw[1:]]
data = [row[1:] for row in csvraw[1:]]

……但看起来还不够Python。

有没有一种更简洁的方法来进行这种自然操作?


Tags: csv标题colgreenblueredcarheaders
3条回答

看看^{}

If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames.

然后你就可以做reader.fieldnames。当然,这只提供列标题。您仍然需要手动分析行标题。

不过,我认为你最初的解决方案相当不错。

现在我明白了,我想要的是用Pandas来完成的最简单(也是最健壮的)。

import pandas as pd
df = pd.read_csv('foo.csv', index_col=0)

如果我愿意,很容易提取:

col_headers = list(df.columns)
row_headers = list(df.index)

否则,在“raw”Python中,我在问题中编写的方法似乎“足够好”。

我知道这个解决方案提供的输出格式比请求的格式要多,但是 很方便。这会将csv行读入字典:

reader = csv.reader(open(parameters_file), dialect)

keys = [key.lower() for key in reader.next()]
for line in reader:
    parameter = dict(zip(keys, cells))

相关问题 更多 >