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 :)
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With