如何使用pandas将csv转换为字典

Dev*_*vEx 5 python csv dictionary pandas

如何使用pandas将csv转换为字典?例如,我有2列,并希望column1为键,column2为值.我的数据如下:

"name","position"
"UCLA","73"
"SUNY","36"

cols = ['name', 'position']
df = pd.read_csv(filename, names = cols)
Run Code Online (Sandbox Code Playgroud)

ank*_*tis 12

由于示例csv-data的第一行是"标题",因此请使用以下单行:

>>> pd.Series.from_csv(filename, header=0).to_dict()
{'UCLA': 73, 'SUNY': 36}
Run Code Online (Sandbox Code Playgroud)

如果您还要包含第1行,请删除header关键字(或将其设置为None).

由于pandas-0.21.0该方法Series.from_csv()已被弃用,因此建议使用pandas.read_csv():

>>> pd.read_csv(filename, index_col=0, squeeze=True).to_dict()
 {'UCLA': '73', 'SUNY': '36'}>
Run Code Online (Sandbox Code Playgroud)

并使用它来包括dict中的第一个标题行:

 >>> pd.read_csv(filename, index_col=0, squeeze=True, header=None).to_dict()
 {'name': 'position', 'UCLA': '73', 'SUNY': '36'}
Run Code Online (Sandbox Code Playgroud)


EdC*_*ica 8

将列转换为列表,然后压缩并转换为dict:

In [37]:

df = pd.DataFrame({'col1':['first','second','third'], 'col2':np.random.rand(3)})
print(df)
dict(zip(list(df.col1), list(df.col2)))
     col1      col2
0   first  0.278247
1  second  0.459753
2   third  0.151873

[3 rows x 2 columns]
Out[37]:
{'third': 0.15187291615699894,
 'first': 0.27824681093923298,
 'second': 0.4597530377539677}
Run Code Online (Sandbox Code Playgroud)