This dataframe is given to me.
My desired output using a dictionary is like this
**Given the following dictionary:-**
d = {'I': 30,'am': 45,'good': 90,'boy': 50,'We':100,'are':70,'going':110}
How to do this using python ..
I have tried like this but have failed 🙁
dataframe['new'] = data['documents'].apply(lambda x: dictionary[x])
Kindly help me out. Thanks in advance.
>Solution :
You can use explode to get words then map with your dict and reshape your dataframe:
MAPPING = {'I': 30,'am': 45,'good': 90,'boy': 50,'We':100,'are':70,'going':110}
df['documents'] = (df['documents'].str.split().explode().map(MAPPING).astype(str)
.groupby(level=0).agg(list).str.join(' '))
print(df)
# Output
id documents
0 0 30 45 90 50
1 1 100 70 110
2 2 30 45 110

