Pandas: using groupby if values in columns are dictionaries
<p>I have dataframe</p>

<pre><code>category  dictionary
moto   {'motocycle':10, 'buy":8, 'motocompetition':7}
shopping   {'buy':200, 'order':20, 'sale':30}
IT   {'iphone':214, 'phone':1053, 'computer':809}
shopping  {'zara':23, 'sale':18, 'sell':20}
IT   {'lenovo':200, 'iphone':300, 'mac':200}
</code></pre>

<p>I need groupby category and as result concatenate dictionaries and choose 3 keys with the biggest values. And next get dataframe, where at the column <code>category</code> I have unique category, and in the column <code>data</code> I have list with keys.</p>

<p>I know, that I can use <code>Counter</code> to concatenate dicts, but I don't know, how do that to categories.
Desire output</p>

<pre><code>category   data
moto   ['motocycle', 'buy', 'motocompetition']
shopping   ['buy', 'sale', 'zara']
IT   ['phone', 'computer', 'iphone']
</code></pre>

<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with custom function with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nlargest.html" rel="nofollow"><code>nlargest</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.tolist.html" rel="nofollow"><code>Index.tolist</code></a>:</p>

<pre><code>df = pd.DataFrame({
'category':['moto','shopping','IT','shopping','IT'],
'dictionary':
[{'motocycle':10, 'buy':8, 'motocompetition':7},
{'buy':200, 'order':20, 'sale':30},
{'iphone':214, 'phone':1053, 'computer':809},
{'zara':23, 'sale':18, 'sell':20},
{'lenovo':200, 'iphone':300, 'mac':200}]})

print (df)
   category                                         dictionary
0      moto  {'motocycle': 10, 'buy': 8, 'motocompetition': 7}
1  shopping              {'sale': 30, 'buy': 200, 'order': 20}
2        IT    {'phone': 1053, 'computer': 809, 'iphone': 214}
3  shopping               {'sell': 20, 'zara': 23, 'sale': 18}
4        IT         {'lenovo': 200, 'mac': 200, 'iphone': 300}


import collections
import functools
import operator

def f(x):
    #some possible solution for sum values of dict
    #http://stackoverflow.com/a/3491086/2901002
    return pd.Series(functools.reduce(operator.add, map(collections.Counter, x)))
             .nlargest(3).index.tolist()

print (df.groupby('category')['dictionary'].apply(f).reset_index())
   category                         dictionary
0        IT          [phone, computer, iphone]
1      moto  [motocycle, buy, motocompetition]
2  shopping                  [buy, sale, zara]
</code></pre>

python pandas dictionary