如果单独的值与Pandas

时间:2017-04-02 02:29:17

标签: python pandas dataframe

我有一个pandas数据框,其中包含订单号,项目以及是否已退回该项目。

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

我还有一份包含已退回订单的清单:

lst = [1001, 1004]

我不确定如何仅更改列表中包含订单号的行的returned列值。任何帮助都会很棒!

1 个答案:

答案 0 :(得分:1)

您可以使用isin方法和loc修改项目:

# 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