Domanda

Suppose I have a Dataframe df :

Label1    Label2        Label3
key1      col1value1    col2value1
key2      col1value2    col2value2
key3      col1value3    col2value3


dict1 = df.set_index('Label1').to_dict() 

This works when we have 2 columns..

Expected Output:

my_dict = {key1: [col1value1,col2value1] , key2: [ col1value2,col2value2] , key3:[col1value3,col2value3] }

Can I use to_dict on Dataframe df to have a key with 2 other columns as values in form of list ??

È stato utile?

Soluzione

Well you could use a dictionary comprehension and iterrows:

print {key:row.tolist() for key,row in df.set_index('Label1').iterrows()}

{'key3': ['col1value3', 'col2value3'],
 'key2': ['col1value2', 'col2value2'], 
 'key1': ['col1value1', 'col2value1']}

Also, I think the following will work too:

df = df.set_index('Label1')
print df.T.to_dict(outtype='list')

{'key3': ['col1value3', 'col2value3'],
 'key2': ['col1value2', 'col2value2'],
 'key1': ['col1value1', 'col2value1']}

Update as of fall 2017; outtype is no longer the keyword argument. Use orient instead:

In [11]: df.T.to_dict(orient='list')
Out[11]: 
{'key1': ['col1value1', 'col2value1'],
 'key2': ['col1value2', 'col2value2'],
 'key3': ['col1value3', 'col2value3']}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top