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

2024-04-26 22:45:38 发布

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

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

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

cols = ['name', 'position']
df = pd.read_csv(filename, names = cols)

Tags: csv数据namepandasdfread字典position
2条回答

将列转换为列表,然后压缩并转换为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}

由于示例csv数据的第一行是“头”, 使用这一行:

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

如果还希望包含第一行,请删除header关键字(或将其设置为None)。

Since pandas-0.21.0 the method Series.from_csv() has been deprecated, and it is suggested to use pandas.read_csv() instead:

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

and use this for including also the 1st header line in the dict:

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

相关问题 更多 >