'Why does deleting/dropping a column/row in pandas cause assigning values to not work?

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?



Solution 1:[1]

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

Solution 2:[2]

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])]

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway
Solution 2 jezrael
Solution 3 ansev