简体   繁体   中英

How to create dictionary when reading csv file?

I've got the following brute force code:

import csv
d = {}
with open(csv_filename, 'r') as csv_file:
    reader = csv.reader(csv_file)
    for row in reader:
        key = row[0]
        d[key] = np.array(
            [[float(x) for x in row[1:4]], [float(x) for x in row[4:7]],
             [float(x) for x in row[7:]]], dtype=float)

Is there a way to rewrite it to avoid [1:4], [4:7] etc?

If I understood correctly you just need to reshape the data.

key = row[0]
d[key] = np.reshape(np.array(row).astype(float), (3, 3))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM