I am trying to convert the dataframe into dictionary in pandas and i got into a problem. When i specify the column names i was able to convert the dataframe into dictionary but when i tried to do without specifying column names but just by column numbers it throws an error.
Here is an example of my dataframe (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
-------------
-----------
So when it tried to convert to dictionary like below, it works fine
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'}
However when i tried with column number, i get error
col2 = list(df1)[1]
dic2 = dict(zip(df.id,df.col2))
print dic2
AttributeError: 'DataFrame' object has no attribute 'col2'
I don't know what am i doing wrong here.
ps. The reason i can't specify the column name is i am trying to insert this code as part of another code and so i don't exactly the names of 2nd column but i definitely know that it is the second column.
you cannot call a column like that if you don't know the name. If you only know the position you could
dict(zip(df.id,df.iloc[:,1]))
would be the second column. if you want the first use 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.