简体   繁体   English

熊猫:csv 到字典

[英]panda: csv to dictionary

I have a csv file in following format:我有一个 csv 文件,格式如下:

id, category编号,类别

1, apple 1、苹果

2, orange 2、橙色

3, banana 3、香蕉

I need to read this file and populate a dictionary which has ids as key and categories as value.我需要阅读这个文件并填充一个字典,其中 id 作为键,类别作为值。

I am trying to use panda, but its to_dict function us returning a dictionary with aa single key-value pair.我正在尝试使用熊猫,但它的 to_dict function 我们返回一个带有单个键值对的字典。 Key is another dictionary containing 1,2,3 as entries and value too is a dictionary containing apple, orange, banana. Key 是另一个包含 1,2,3 作为条目的字典,而 value 也是一个包含 apple、orange、banana 的字典。

What I want is three key-value entriesm like 1 -> apple, 2 -> ornge, 3 -> banana.我想要的是三个键值条目,例如 1 -> apple、2 -> ornge、3 ->banana。

You can create index by first column and then convert Series df['category'] to dictionary:您可以按第一列创建索引,然后将 Series df['category']转换为字典:

df = pd.read_csv('file.csv', index_col=0)

d = df['category'].to_dict()

Or if only 2 columns csv is possible create Series by index_col=0 and squeeze=True parameters and convert to dicts:或者,如果只有 2 列 csv 可以通过index_col=0squeeze=True参数创建系列并转换为字典:

d = pd.read_csv('file.csv', index_col=0, squeeze=True).to_dict()

Or if more columns and dont need index by first column use:或者,如果更多列并且不需要按第一列使用索引:

df = pd.read_csv('file.csv')

d = df.set_index('id')['category'].to_dict()

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

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