python - 如果单独的值与 Pandas 中的列表匹配,则更新单元格值

标签 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]

我不确定如何仅更改列表中具有订单号的行的返回列值。任何帮助都会很棒!

最佳答案

您可以使用 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

关于python - 如果单独的值与 Pandas 中的列表匹配,则更新单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43163994/

相关文章:

python - 对 Pandas 时间序列数据进行重新采样,仅保留每行的有效数字

python - Pandas:在应用函数中获取分组索引

python - 将列表列分解为多列

python - Pandas -填充nans直到第一个非NULL值

python - 将 1 channel 骨架图像叠加到 3 channel RGB 图像上

python - flask_sqlalchemy : AbstractConcreteBase not mapped until subclass is queried

python - 在朴素贝叶斯实现中很难获得正确的后验值

python - 如何为 pytest 创建 HTML 报告?

python - Pandas:如何添加缺少的标题列

python - 在 pandas/python 中转置 DataFrame,但不是所有列