user2466888
user2466888

Reputation: 699

Update cell value if separate value matches list in Pandas

I have a pandas dataframe with order numbers, items, and if the item was returned or not.

df = pd.DataFrame({'order_number': [1001, 1002, 1003, 1004], 
'item': ['table', 'chair', 'sofa', 'armchair'], 'returned': [0,0,0,0]})


        item  order_number  returned
0     table          1001       0
1     chair          1002       0
2      sofa          1003       0
3  armchair          1004       0

I also have a list with orders that have been returned:

lst = [1001, 1004]

I'm not sure how to change the returned column value for only those rows with order numbers in the list. Any help would be great!

Upvotes: 2

Views: 1882

Answers (1)

akuiper
akuiper

Reputation: 215057

You can use isin method with loc to modify the items:

# use isin method to create a logical series and use loc to modify return column at 
# corresponding rows
df.loc[df.order_number.isin(lst), "returned"] = 1

df
#      item   order_number  returned
#0    table           1001  1
#1    chair           1002  0
#2     sofa           1003  0
#3 armchair           1004  1

Upvotes: 3

Related Questions