So basically this code:
df.iloc[df[(df.Handcap == 2) | (df.Handcap == 3 ) | (df.Handcap == 4)].Handcap.index, 11] = 1
Only works, aka assigns values to some cells that satisfy a certain condition, if I didn't use the drop
or delete
methods before I run this code in pandas, such as:
del df['ID']
Why does this happen and how can I overcome this issue?
CodePudding user response:
You can use loc
with the reverse approach:
mask = (df.Handcap == 2) | (df.Handcap == 3 ) | (df.Handcap == 4)
df.loc[mask, df.columns[11]] = 1
CodePudding user response:
Use DataFrame.iloc
with converting mask by Series.isin
to numpy array:
df.iloc[df.Handcap.isin([2,3,4]).to_numpy(), 11] = 1
If need remove rowsmatch or not match by condition in boolean indexing
:
df1 = df[df.Handcap.isin([2,3,4])]
df2 = df[~df.Handcap.isin([2,3,4])]
CodePudding user response:
You need use boolean indexing
with DataFrame.loc
, wihtout .index
. We could also use Series.isin
df.loc[df.Handcap.isin([2,3,4]), df.columns[11]] = 1