使用布尔索引改变值

Using Boolean indexing to change value

我有一个如下所示的数据集:

VendorAccount   FiscalPeriod    LCC
729616,             1,          False
729616,             2,          False
0,                  2,          False
1,                  4,          False

我尝试使用这条线:

df['LCC'][(df['VendorAccount'] == 729616) & df['FiscalPeriod'] >1] = True

让它看起来像这样:

VendorAccount   FiscalPeriod    LCC
729616,             1,          False
729616,             2,          True
0,                  2,          False
1,                  4,          False

脚本运行但未进行任何更改。谁能告诉我哪里出错了?

& 运算符的优先级高于 >,因此您的原始代码等同于:

df['LCC'][((df['VendorAccount'] == 729616) & df['FiscalPeriod']) > 1] = True

要正确更新数据框,您应该改用以下代码:

df['LCC'][(df['VendorAccount'] == 729616) & (df['FiscalPeriod'] > 1)] = True