我正在尝试将数据框转换为pandas中的字典,我遇到了问题。当我指定列名称时,我能够将数据帧转换为字典,但是当我尝试不指定列名但仅通过列号时,它会抛出错误。
以下是我的数据框(df1)
的示例 id Crub
0 At1NC000060_TBH_1 Not found
1 At1NC005280_TBH_1 Known_Gene_Sense
2 At1NC007770_TBH_1 Known_Gene_Sense
3 At1NC018710_TBH_1 Not found
4 At1NC027560_TBH_1 Known_Gene_Antisense
5 At1NC030450_TBH_1 Known_Gene_Sense
6 At1NC031370_TBH_1 Known_Gene_Antisense
7 At1NC035150_TBH_1 Known_Gene_Antisense
8 At1NC046250_TBH_1 Known_Gene_Sense
-------------
-----------
所以当它试图像下面这样转换为字典时,它可以正常工作
dic1 = dict(zip(df.id,df.Crub))
print(dic1)
{'At3NC025390_TBH_1': 'Known_Gene_Antisense', 'At1NC064880_TBH_1': 'Not found', 'At1NC035150_TBH_1': 'Known_Gene_Antisense', 'At3NC044300_TBH_1': 'Known_Gene_Antisense', 'At2NC000610_TBH_1': 'Known_Gene_Antisense'}
然而,当我尝试使用列号时,我收到错误
col2 = list(df1)[1]
dic2 = dict(zip(df.id,df.col2))
print dic2
AttributeError: 'DataFrame' object has no attribute 'col2'
我不知道我在这里做错了什么。
PS。我无法指定列名的原因是我试图将此代码作为另一个代码的一部分插入,因此我不完全是第二列的名称,但我肯定知道它是第二列。
答案 0 :(得分:1)
dict(zip(df.id,df.iloc[:,1]))
将是第二列。如果你想第一次使用0