简体   繁体   中英

How to convert CSV file to python dictionary

If I have a CSV (info.csv) file below:

180101, S1, -1

180101, S2, 15

180102, S4, -5

180103, S1, -5

...

The columns mean "date", "code", "info1" respectively.

I want to convert new code (csv file, newcode.scv) matching in original data.

such as new code mapping is below:

180101, N1

180102, N2

180103, W1

...

Regard it as a one to one relation, no duplicates.

So new data from it:

180101, N1, -1

180101, N2, 15

180102, N2, -5

180103, W1, -5

Is there a nine fancy way of converting?

One way is to use pandas , which specializes in vectorised computations. A pure csv method will likely be loop-based and inefficient.

import pandas as pd

df = pd.read_csv('info_in.csv', sep=', ', engine='python',
                 header=None, names=['date', 'code', 'info1'])

#      date code  info1
# 0  180101   S1     -1
# 1  180101   S2     15
# 2  180102   S4     -5
# 3  180103   S1     -5

d = {'S1': 'N1', 'S2': 'N2', 'S4': 'W1'}
df['code'] = df['code'].map(d)
df.to_csv('info_out.csv', index=False)

#      date code  info1
# 0  180101   N1     -1
# 1  180101   N2     15
# 2  180102   W1     -5
# 3  180103   N1     -5

The csv module of the standard library has a bunch of useful functions for dealing with csv files including easy ways to both read and write them. DictReader is the one you'd want to look at for converting entries into a dictionary.

csv module documentation

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