1

I have the below sample data:

class   name
Pref    Ab
Val     BE
Base    es
Pref    Cw
Base    SS

This data is in a dataframe and I need to create a mapping for class : name as shown below:

Pref : ['Ab','Cw'],
Val  : ['BE'],
Base : ['es','SS']

This will be a dictionary which will contain a mapping for class and it's component names.The key will be class and it's values will be the names in that class, so a list of values for each class, where the list length might vary for each class. Can someone please help me with this?

1 Answer 1

1

You'd be looking for a groupby + to_dict operation -

r = df.groupby('class').name.apply(list).to_dict()

Or,

r = df.groupby('class').name.agg(pd.Series.tolist).to_dict()

r
{'Base': ['es', 'SS'], 'Pref': ['Ab', 'Cw'], 'Val': ['BE']}

How it works -

  • The class column consists of 3 categories. We want each category as an index.
  • Furthermore, each element in the name column would need to be grouped by class and present in a list

It follows that a groupby operation is the most straightforward thing to do here. Group and apply/aggregate with list to get a series with index as so -

class
Base    [es, SS]
Pref    [Ab, Cw]
Val         [BE]
Name: name, dtype: object

Calling to_dict on this gives you what you want.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.