简体   繁体   English

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

[英]Reading csv file as dictionary using pandas

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. 我希望列'A'中的值是键。 How do I do that ie get answer like this: 我该怎么做,即得到这样的答案:

{'test':'23', 'try':'34'}
dt = pandas.read_csv('file.csv', index_col=1, skiprows=1).T.to_dict()

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: 转换为dictioanry:

print(dict(df.values))

Will give: 会给:

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

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

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