Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Replace Pandas Series with Dictionary Values

I want to link my dictionary values to pandas series object. I have already tried replace method and map method still no luck.

As per link: Replace values in pandas Series with dictionary

Still not working, my sample pandas looks like:

index                    column
0                      ESL Literacy
1    Civics  Government Team Sports
2      Health  Wellness Team Sports
3              Literacy Mathematics
4                       Mathematics

Dictionary:

{'civics': 6,
 'esl': 5,
 'government': 7,
 'health': 8,
 'literacy': 1,
 'mathematics': 4,
 'sports': 3,
 'team': 2,
 'wellness': 9}

Desired Output:

0 [5,1]
1 [6,7,2,3]
2 [8,9,2,3]
3 [1,4]
4 [4]

Any help would be appreciated. Thank you :)

like image 206
Arjunsai Avatar asked Dec 22 '22 22:12

Arjunsai


2 Answers

A fun solution

s=df.column.str.get_dummies(' ')
s.dot(s.columns.str.lower().map(d).astype(str)+',').str[:-1].str.split(',')
Out[413]: 
0          [5, 1]
1    [6, 7, 3, 2]
2    [8, 3, 2, 9]
3          [1, 4]
4             [4]
dtype: object

Or in pandas 0.25.0 we can use explode:

df.column.str.split().explode().str.lower().map(d).groupby(level=0).agg(list)
Out[420]: 
0          [5, 1]
1    [6, 7, 2, 3]
2    [8, 9, 2, 3]
3          [1, 4]
4             [4]
Name: column, dtype: object
like image 53
BENY Avatar answered Jan 11 '23 21:01

BENY


Using str.lower, str.split, and a comprehension.

u = df['column'].str.lower().str.split('\s+')

pd.Series([[d.get(word) for word in row] for row in u])

0          [5, 1]
1    [6, 7, 2, 3]
2    [8, 9, 2, 3]
3          [1, 4]
4             [4]
dtype: object
like image 39
user3483203 Avatar answered Jan 11 '23 22:01

user3483203