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>

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

def top3(x):
    return x.dropna().sort_values().tail(3)[::-1].index.tolist()

df.dictionary.apply(pd.Series).groupby(df.category).sum().apply(top3, axis=1)

category
IT                   [phone, computer, iphone]
moto        [motorcycle, buy, motocompetition]
shopping                     [buy, sale, zara]
dtype: object
</code></pre>

python pandas dictionary