简体   繁体   English

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

[英]how to convert csv to dictionary using pandas

How can I convert a csv into a dictionary using pandas?如何使用 Pandas 将 csv 转换为字典? For example I have 2 columns, and would like column1 to be the key and column2 to be the value.例如,我有 2 列,并且希望 column1 是键,而 column2 是值。 My data looks like this:我的数据如下所示:

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

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

Since the 1st line of your sample csv-data is a "header", you may read it as pd.Series using the squeeze keyword of pandas.read_csv() :由于您的示例 csv-data 的第一行是“标题”,您可以使用pandas.read_csv()squeeze关键字将其读取为pd.Series

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

If you want to include also the 1st line, remove the header keyword (or set it to None ).如果您还想包括第一行,请删除header关键字(或将其设置为None )。

Convert the columns to a list, then zip and convert to a 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}

ankostis answer in my opinion is the most elegant solution when you have the file on disk.当您将文件保存在磁盘上时,我认为ankostis 答案是最优雅的解决方案。

However, if you do not want to or cannot go the detour of saving and loading from the file system, you can also do it like this:但是,如果您不想或不能走从文件系统保存和加载的弯路,您也可以这样做:

df = pd.DataFrame({"name": [73, 36], "position" : ["UCLA", "SUNY"]})

series = df["position"]
series.index = df["name"]
series.to_dict()

Result:结果:

{'UCLA': 73, 'SUNY': 36}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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