Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Series.map() that works with a dictionary of key-list pairs #58108

Open
1 of 3 tasks
kbmorales opened this issue Apr 1, 2024 · 1 comment
Open
1 of 3 tasks

ENH: Series.map() that works with a dictionary of key-list pairs #58108

kbmorales opened this issue Apr 1, 2024 · 1 comment
Labels
Closing Candidate May be closeable, needs more eyeballs Enhancement Needs Triage Issue that has not been reviewed by a pandas team member

Comments

@kbmorales
Copy link

kbmorales commented Apr 1, 2024

Feature Type

  • Adding new functionality to pandas

  • Changing existing functionality in pandas

  • Removing existing functionality in pandas

Problem Description

Dictionaries are perfect for mapping, but I often have the situation where I need to reassign multiple values to a single key value. However, Series.map() does the opposite, by searching through the keys and assigning the values.

Feature Description

I use this currently:

def flip_map(col, dct):
    """
    Inverts a dictionary of key, value pairs where the values are lists
    """
    exp_dct = pd.Series(dct).explode()
    flip_dct = dict(zip(exp_dct,exp_dct.index))
   
    return col.map(flip_dct).fillna(col)

Alternative Solutions

I think the above using base python and Series.explode() should do it

Additional Context

No response

@kbmorales kbmorales added Enhancement Needs Triage Issue that has not been reviewed by a pandas team member labels Apr 1, 2024
@Aloqeely
Copy link
Member

Aloqeely commented Apr 1, 2024

Thanks for the request - I think there are many ways to modify your dictionary format before passing it to Series.map to get your desired result and I also don't think that dictionary format is particularly readable, so I'm not a fan of this

flip_map is one way to achieve your desired result, but a nested loop will do the job and I think is more readable:

flipped = {}
for key, value_list in dictionary.items():
    for item in value_list:
        flipped[item] = key

And if you want a 1 liner, you can achieve that with a dict comprehension:

flipped = {item: key for key, value_list in dictionary.items() for item in value_list}

@Aloqeely Aloqeely added the Closing Candidate May be closeable, needs more eyeballs label May 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Closing Candidate May be closeable, needs more eyeballs Enhancement Needs Triage Issue that has not been reviewed by a pandas team member
Projects
None yet
Development

No branches or pull requests

2 participants