Pandas df to dictionary with values as python lists aggregated from a df column
<p>I have a pandas df containing 'features' for stocks, which looks like this: </p>

<p><a href="https://i.stack.imgur.com/fekQs.png" rel="nofollow"><img src="https://i.stack.imgur.com/fekQs.png" alt="features for stocks previous to training neural net"></a></p>

<p>I am now trying to create a dictionary with <strong>unique sector</strong> as <strong>key</strong>, and a <strong>python list of tickers</strong> for that unique sector as <strong>values</strong>, so I end up having something that looks like this:</p>

<pre><code>{'consumer_discretionary': ['AAP',
  'AMZN',
  'AN',
  'AZO',
  'BBBY',
  'BBY',
  'BWA',
  'KMX',
  'CCL',
  'CBS',
  'CHTR',
  'CMG',
</code></pre>

<p>etc.</p>

<p>I could iterate over the pandas df rows to create the dictionary, but I prefer a  more pythonic solution. Thus far, this code is a partial solution:</p>

<pre><code>df.set_index('sector')['ticker'].to_dict()
</code></pre>

<p>Any feedback is appreciated.</p>

<p><strong>UPDATE:</strong></p>

<p>The solution by @wrwrwr </p>

<pre><code>df.set_index('ticker').groupby('sector').groups
</code></pre>

<p>partially works, but it returns a <strong>pandas series</strong> as a the value, instead of a <strong>python list</strong>. Any ideas about how to transform the pandas series into a python list in the same line and w/o having to iterate the dictionary?</p>

<p>Wouldn't <code>f.set_index('ticker').groupby('sector').groups</code> be what you want?</p>

<p>For example:</p>

<pre><code>f = DataFrame({
        'ticker': ('t1', 't2', 't3'),
        'sector': ('sa', 'sb', 'sb'),
        'name': ('n1', 'n2', 'n3')})

groups = f.set_index('ticker').groupby('sector').groups
# {'sa': Index(['t1']), 'sb': Index(['t2', 't3'])}
</code></pre>

<p>To ensure that they have the type you want:</p>

<pre><code>{k: list(v) for k, v in f.set_index('ticker').groupby('sector').groups.items()}
</code></pre>

<p>or:</p>

<pre><code>f.set_index('ticker').groupby('sector').apply(lambda g: list(g.index)).to_dict()
</code></pre>

python pandas dictionary