Python09
Python09

Reputation: 115

Replace values of one column based off list of IDs in another column

I want to replace values of the Store column but only for specific IDs in a list (this could be a list of thousands of IDs)

ID#     Fruit      Store 
1234    Apple      Whole Foods
4567    Banana     Trader Joe's
6789    Apple      Trader Joe's
7890    Kiwi       Shop Rite

I want only ID# in a list ['1234,'6789','7890'] Store Name to be changed to "Walmart"

Desired Dataframe:

ID#     Fruit      Store 
1234    Apple      Walmart
4567    Banana     Trader Joe's
6789    Apple      Walmart
7890    Kiwi       Walmart

What is the quickest way to do this in python/pandas?

Thanks!

Upvotes: 0

Views: 895

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150745

Use loc access with isin:

df.loc[df['ID#'].isin( ['1234','6789','7890']), 'Store'] = 'Walmart'

Output:

    ID#   Fruit         Store
0  1234   Apple       Walmart
1  4567  Banana  Trader Joe's
2  6789   Apple       Walmart
3  7890    Kiwi       Walmart

Upvotes: 2

Related Questions