4

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 :)

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

4

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

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.