Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping values to each item in a list in pandas

I have a pandas dataframe column with a list of names like so:

Names
Roger Williams, Anne Graham
Joe Smoe, Elliot Ezekiel
Todd Roger 

And a dictionary with user_ids:

map = {Roger Williams: 1234, Anne Graham: 4892, Joe Smoe: 898, Elliot Ezekiel: 8458, Todd Roger: 856}

I need to use pandas .map function to map each name in the list with the user_id like so:

Names                           user_id
Roger Williams, Anne Graham     1234, 4892
Joe Smoe, Elliot Ezekiel        898, 8458
Todd Roger                      856

Can someone help me accomplish this? I'm having a real hard time with it. Thanks!

like image 916
staten12 Avatar asked May 30 '17 20:05

staten12


3 Answers

In [124]: mapping
Out[124]:
{'Anne Graham': 4892,
 'Elliot Ezekiel': 8458,
 'Joe Smoe': 898,
 'Roger Williams': 1234,
 'Todd Roger': 856}

In [125]: df
Out[125]:
                         Names
0  Roger Williams, Anne Graham
1     Joe Smoe, Elliot Ezekiel
2                   Todd Roger

In [126]: df.replace(mapping.keys(), list(map(str, mapping.values())), regex=True)
Out[126]:
        Names
0  1234, 4892
1   898, 8458
2         856

if you have a list of strings:

In [131]: df
Out[131]:
                           Names
0  [Roger Williams, Anne Graham]
1     [Joe Smoe, Elliot Ezekiel]
2                   [Todd Roger]

In [133]: df.Names.apply(', '.join).replace(mapping.keys(), list(map(str, mapping.values())), regex=True)
Out[133]:
0    1234, 4892
1     898, 8458
2           856
Name: Names, dtype: object
like image 39
MaxU - stop WAR against UA Avatar answered Sep 28 '22 02:09

MaxU - stop WAR against UA


Leverage pd.Series and astype(str)

df.replace(pd.Series(m).astype(str), regex=True)

        Names
0  1234, 4892
1   898, 8458
2         856

Setup

df = pd.DataFrame({
        'Names': [
            'Roger Williams, Anne Graham',
            'Joe Smoe, Elliot Ezekiel',
            'Todd Roger'
         ]
    })

m = {
    'Roger Williams': 1234, 'Anne Graham': 4892,
    'Joe Smoe': 898, 'Elliot Ezekiel': 8458, 'Todd Roger': 856
}
like image 179
piRSquared Avatar answered Sep 28 '22 03:09

piRSquared


def get_values(g):
    return ", ".join([map[x] for x in g])

df['Names'] = df['Names'].map(get_values)

0    1234, 4892
1     898, 8458
2           856
Name: Names, dtype: object
like image 40
Riley Hun Avatar answered Sep 28 '22 02:09

Riley Hun