'Replace values in a dataframe in python with the dictionary, where the dictionary values are lists

import pandas as pd
import yfinance as yf

msft = yf.Ticker("MSFT")

df= msft.recommendations

df['ToGrade_new'] = df['To Grade'].str.lower().str.replace('[^\w\s]','')

new_df = df['ToGrade_new'].str.split(expand=True).stack().value_counts().reset_index()

new_df.columns = ['Word', 'Frequency']

newdict = {'VGood': ['buy', 'strong'], 'Good': ['moderate', 'overweight'], 'Okay': ['hold', 'equalweight', 'market','neutral'], 'Bad': ['underperform','moderatesell','underweight'], 'VBad':['sell']}

I need help here. I want to replace the Word column in the new_df dataframe with the words I have for keys in the newdict dictionary. Any help would be appreciated.

If new_df looks like this

Word Frequency

buy 121

overweight 82 ...

then it should be replaced by

Word Frequency

VGood 121

Good 82 ...



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source