pandas 使用pandas将csv文件作为字典读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33620982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:12:02  来源:igfitidea点击:

Reading csv file as dictionary using pandas

pythondictionarypandas

提问by user308827

I have the foll. csv with 1st row as header:

我有一个愚蠢的。第一行作为标题的 csv:

A      B
test    23
try     34

I want to read in this as a dictionary, so doing this:

我想把它当作字典来读,所以这样做:

dt = pandas.read_csv('file.csv').to_dict()

However, this reads in the header row as key. I want the values in column 'A' to be the keys. How do I do that i.e. get answer like this:

但是,这在标题行中读取为键。我希望“A”列中的值作为键。我该怎么做,即得到这样的答案:

{'test':'23', 'try':'34'}

回答by Alexander

dt = pandas.read_csv('file.csv', index_col=1, skiprows=1).T.to_dict()

回答by Leb

Duplicating data:

复制数据:

import pandas as pd
from io import StringIO

data="""
A      B
test    23
try     34
"""

df = pd.read_csv(StringIO(data), delimiter='\s+')

Converting to dictioanry:

转换为字典:

print(dict(df.values))

Will give:

会给:

{'try': 34, 'test': 23}