【问题标题】:Using Boolean indexing to change value使用布尔索引更改值
【发布时间】:2021-12-12 01:57:15
【问题描述】:

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

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

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

【问题讨论】:

    标签: python dataframe boolean


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-06
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 2014-06-16
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多