1

I have a dataframe, which I want to convert to a dictionary in such a way that col1 becomes the key and col2 becomes the value. Also, there can be multiple occurrences of a value in 1st col, in which case I want to store the counts in the form of a list corresponding to that value of col1 as key. So basically how can I perform this conversion -

area count

10   7
10   3
10   1
20   5
30   2
30   1
40   3

{
'10' : [7,3,1],
'20' : '5',
'30' : [2,1],
'40' : 3
}

Thanks in advance!

user3024292
  • 97
  • 2
  • 12

1 Answers1

2

If i understood your comment correctly you can do it this way:

In [35]: df
Out[35]:
   area  count  probability
0    10      7     0.116754
1    10      3     0.703845
2    10      1     0.368201
3    20      5     0.550190
4    30      2     0.037654
5    30      1     0.379534
6    40      3     0.320877

In [36]: df.sort_values('probability', ascending=False).groupby('area')['count'].apply(list).to_dict()
Out[36]: {10: [3, 1, 7], 20: [5], 30: [1, 2], 40: [3]}
Community
  • 1
  • 1
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
  • That's exactly what I wanted to do!Thanks! Can we convert this dictionary back to dataframe? – user3024292 Dec 11 '16 at 12:38
  • @user3024292, you are welcome! It's going to be bit tricky to convert it back to DF - you'd better ask a new question with small data samples (especially for expected DF) – MaxU - stand with Ukraine Dec 11 '16 at 12:40
  • Can't ask another question before 90min! So I'll try to explain this here instead.For eg if I dont do apply(list).to_dict() I get the following output: \n df.sort_values('probability', ascending=False).groupby('area')['count'] Can we convert the groupby object to a dataframe? – user3024292 Dec 11 '16 at 12:57
  • @user3024292, it's not clear to me what kind of result DF do you expect to get when converting `groupby` object to DF... – MaxU - stand with Ukraine Dec 11 '16 at 12:59
  • Found the answer here: http://stackoverflow.com/questions/10373660/converting-a-pandas-groupby-object-to-dataframe Thanks anyways! – user3024292 Dec 11 '16 at 13:01
  • 1
    @user3024292, you may also want to check examples in Pandas docs: http://pandas.pydata.org/pandas-docs/stable/groupby.html#groupby – MaxU - stand with Ukraine Dec 11 '16 at 13:04