简体   繁体   中英

Using Boolean indexing to change value

I have a dataset that looks like this:

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

I attempted to use this line:

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

to make it look like this:

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

The script runs but no changes are being made. Can anyone advise me on where I am going wrong?

& operator has higher precedence than > , hence your original code is equivalent to this:

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

To update the dataframe correctly you should use the following code instead:

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

First You need convert FiscalPeriod to int then you can run your check like below:

>>> df['FiscalPeriod'] = df['FiscalPeriod'].str[0].astype(int)
>>> m = (df['VendorAccount'] == '729616,') & (df['FiscalPeriod'] > 1)
>>> df.loc[m, 'LCC'] = True 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM