[英]append column in dataframe to dictionary python
I want to set two columns from my dataframe (EisDat_cvs) as dictionary key and value in python, and everything works fine using this code: 我想将数据框(EisDat_cvs)中的两列设置为python中的字典键和值,并且使用此代码,一切正常:
dict_EisukeID_HMDB = EisDat_cvs.set_index('Unnamed: 28')['Unnamed: 26'].to_dict()
However now I want to append two columns as values and one as key in the dictionary, and I tried to modify the previous one as: 但是,现在我想在字典中添加两列作为值,一列作为键,并且尝试将前一列修改为:
dict_EisukeID_HMDB = EisDat_cvs.set_index('Unnamed: 28')['Unnamed: 26', 'Unnamed: 1'].to_dict()
But python throws me a key error... 但是python抛出了一个关键错误...
EDIT 编辑
I have a dataframe EisDat_cvs, of which I am considering 3 columns (Unnamed: 28, Unnamed: 26, Unnamed: 1). 我有一个数据框EisDat_cvs,正在考虑其中的3列(未命名:28,未命名:26,未命名:1)。 And I want to get a dictionary that takes the values in column 28 as my keys, and values in column 26 and 1 as values in the dictionary. 我想获得一个字典,将第28列中的值作为我的键,将第26列和1中的值作为字典中的值。 Something like this: 像这样:
Unnamed: 28, Unnamed: 26, Unnamed: 1
bla. 1 90
cra 2 12
ta 3 12
and my output should look like 我的输出应该像
dict_EisukeID_HMDB = { 'bla': '1', '90'
'cra': '2', '12'
'ta': '3', '12'}
You can try this: 您可以尝试以下方法:
dict(zip(
EisDat_cvs['Unnamed: 28'],
zip(EisDat_cvs['Unnamed: 26'], EisDat_cvs['Unnamed: 1'])
))
The issue you had was not with to_dict()
but instead by passing the columns as a tuple, you are trying to access the dataframe through a hierarchal column structure , which if your dataframe does not have, will throw a KeyError
. 您遇到的问题与to_dict()
,而是通过将列作为元组传递,您正尝试通过层次结构的列结构访问数据框,如果您的数据框没有该结构 ,则将抛出KeyError
。
Hierarchal columns example: 层次列示例:
df = pd.DataFrame({
("A", "A0"): [10, 30, 50, 70],
("A", "A1"): [11, 31, 51, 71],
("B", "B0"): [20, 40, 60, 80],
("B", "B1"): [21, 41, 61, 81]
})
print(df["A", "A0"])
Output: 输出:
0 10
1 30
2 50
3 70
Name: (A, A0), dtype: int64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.