简体   繁体   English

使用熊猫将CSV保存到带有列表的字典作为值

[英]Save CSV to dictionary with a list as the value using pandas

My CSV file looks something like this: 我的CSV文件如下所示:

Version,1,2,3,4,5
Letter,A,B,C,D,E

Version and letter are both the keys I want in the dictionary which I read in using indexcol = 0. However, I want to save these values into a dictionary like this: 版本和字母都是我要使用indexcol = 0读入的字典中的键。但是,我想将这些值保存到字典中,如下所示:

{Version: ["1,2,3,4,5"], Letter: ["A,B,C,D,E"]}

How would I do this using pandas? 我该如何使用熊猫呢? Thanks so much for your help. 非常感谢你的帮助。

Since you have the keys in rows, one simple way is to transpose the csv file and then converting columns to list followed by zip and to dictionary 由于密钥在行中,一种简单的方法是转置csv文件,然后将列转换为list ,然后将zip转换为字典

df = pandas.read_csv("filename.csv").transpose()
dictionary = dict(zip(list(df.column_name1), list(df.column_name2)))

Other efficient way and if you have too many values in rows to enter each column name then you can try: 其他有效的方法,如果行中的值太多,无法输入每个列的名称,则可以尝试:

df = pandas.read_csv("filename.csv").transpose().to_dict()

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

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