How can i create a dictionary from a dataframe without specifying column names in pandas?
<p>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. </p>

<p>Here is an example of my dataframe (df1)</p>

<pre><code>                       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
    -------------
    -----------
</code></pre>

<p>So when it tried to convert to dictionary like below, it works fine</p>

<pre><code>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'}
</code></pre>

<p>However when i tried with column number, i get error</p>

<pre><code>col2 = list(df1)[1]
dic2 = dict(zip(df.id,df.col2))
print dic2

AttributeError: 'DataFrame' object has no attribute 'col2'
</code></pre>

<p>I don't know what am i doing wrong here.</p>

<p>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.</p>

<p>you cannot call a column like that if you don't know the name. If you only know the position you could</p>

<pre><code> dict(zip(df.id,df.iloc[:,1]))
</code></pre>

<p>would be the second column. if you want the first use 0</p>

python pandas dictionary