TypeError: Cannot perform 'ror_' with a dtyped [float64] array and scalar of type [bool]

Viewed 3747

I want to iterate through the column df['fyear'] and delete any row for which fyear isn't equal to either 2009, 2019, or 2020. But this error comes up:

TypeError: Cannot perform 'ror_' with a dtyped [float64] array and scalar of type [bool]

df = pd.DataFrame({'fyear': [2009, 2019, 2020, 2020, 2019, 2009, 2000, 2000, 2001]})

for row in df.iterrows():
    if df["fyear"] != 2009 | df["fyear"] !=2019 | df["fyear"] !=2020:
        df.drop(row)

EDIT The optimal solution is using boolean indexing with either the operators & or |

df = df[(df['fyear'] == 2009) | (df['fyear'] == 2019) | (df['fyear'] == 2020)]
1 Answers

Python uses or as infix keyword

df["fyear"] != 2009 or df["fyear"] !=2019 or df["fyear"] !=2020

Or even better (more pythonic and also readable)

df["fyear"] not in (2009,2019,2020)
Related