I have this DataFrame:
manufacturer description
0 toyota toyota, gmc 10 years old.
1 NaN gmc, Motor runs and drives good.
2 NaN Motor old, in pieces.
3 NaN 2 owner 0 rust. Cadillac.
And I want to fill the NaN values with keyword taken from the description. To that end I created a list with the keywords I want:
keyword = ['gmc', 'toyota', 'cadillac']
Finally, I want to loop over each row in the DataFrame. Split the contents from the "description" column in each row and, if that word is also in the "keyword" list, add it in the "manufacturer" column. As an example, it would look like this:
manufacturer description
0 toyota toyota, gmc 10 years old.
1 gmc gmc, Motor runs and drives good.
2 NaN Motor old, in pieces.
3 cadillac 2 owner 0 rust. Cadillac.
Thanks to someone in this community I could improve my code to this:
import re
keyword = ['gmc', 'toyota', 'cadillac']
bag_of_words = []
for i, description in enumerate(test3['description']):
bag_of_words = re.findall(r"""[A-Za-z\-]+""", test3["description"][i])
for word in bag_of_words:
if word.lower() in keyword:
test3.loc[i, 'manufacturer'] = word.lower()
But I realized that the first row also changed values even though it was not NaN:
manufacturer description
0 gmc toyota, gmc 10 years old.
1 gmc gmc, Motor runs and drives good.
2 NaN Motor old, in pieces.
3 cadillac 2 owner 0 rust. Cadillac.
I would like to only change the NaN values but when I try to add:
if word.lower() in keyword and test3.loc[i, 'manufacturer'] == np.nan:
It doesn't have any effect.