2

I have a pandas df containing 'features' for stocks, which looks like this:

features for stocks previous to training neural net

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

{'consumer_discretionary': ['AAP',
  'AMZN',
  'AN',
  'AZO',
  'BBBY',
  'BBY',
  'BWA',
  'KMX',
  'CCL',
  'CBS',
  'CHTR',
  'CMG',

etc.

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:

df.set_index('sector')['ticker'].to_dict()

Any feedback is appreciated.

UPDATE:

The solution by @wrwrwr

df.set_index('ticker').groupby('sector').groups

partially works, but it returns a pandas series as a the value, instead of a python list. 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?

1 Answer 1

4

Wouldn't f.set_index('ticker').groupby('sector').groups be what you want?

For example:

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'])}

To ensure that they have the type you want:

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

or:

f.set_index('ticker').groupby('sector').apply(lambda g: list(g.index)).to_dict()
5
  • Thank you @wrwrwr, almost there! your solution is excellent but it does not quite return a python list as the value, but a pandas series as the value. I could take it from here and loop the dictionary to transform the pandas series into a list, but again, that's what I was avoiding. I'm looking for a pythonic, one liner solution. Do you know how to transform the pandas series into a python list in the same line? i.e: f.set_index('ticker').groupby('sector').groups.tolist() (that does not work) Oct 19, 2016 at 22:50
  • use list() method to convert to list
    – MMF
    Oct 19, 2016 at 23:15
  • 1
    I'm not sure why are you getting series as values, but still extended the answer with some rather brutal approaches to enforcing that they are lists.
    – wrwrwr
    Oct 19, 2016 at 23:23
  • 1
    Updated for Pandas 0.19 (which seems to have switched from plain lists to indices for groups values).
    – wrwrwr
    Oct 20, 2016 at 0:30
  • Great answer. Thanks Oct 20, 2016 at 2:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.