Home > Net >  filter out a dictionary within NOT isin
filter out a dictionary within NOT isin

Time:10-27

I read a dataframe into a dictionary. Earlier, I was filtering out all the rows which are .isin(['I1','I2','I3','I4']). This worked correctly

df = {}
df['cgo_eafapo_t'] = pd.read_sql_table('cgo_eafapo_t', engine, schema_z2,
                                    columns = cols)
df['cgo_eafapo_t'] = df['cgo_eafapo_t'][df['cgo_eafapo_t']['art_kennz'].isin(['I1','I2','I3','I4'])]

However, now I want to filter out all rows which are NOT IN (['I1','I2','I3','I4']). How can I do so? I know we can use a ~ but I am not sure where exactly. I tried this but it threw a Type error:

df['cgo_eafapo_t'] = ~df['cgo_eafapo_t'][df['cgo_eafapo_t']['art_kennz'].isin(['I1','I2','I3','I4'])]
ufunc 'invert' not supported for the input types, and the inputs

Also tried putting the sign before art_kennz but that threw an error too

df['cgo_eafapo_t'] = df['cgo_eafapo_t'][df['cgo_eafapo_t'](~['art_kennz'].isin(['I1','I2','I3','I4']))]
attribute error list object has no attribute isin

This did not work either:

df['cgo_eafapo_t'] = df['cgo_eafapo_t']~([df['cgo_eafapo_t']['art_kennz'].isin(['I1','I2','I3','I4'])])

CodePudding user response:

Use ~ before condition:

df['cgo_eafapo_t'] = df['cgo_eafapo_t'][~df['cgo_eafapo_t']['art_kennz'].isin(['I1','I2','I3','I4'])]

Better is select by DataFrame.loc:

df['cgo_eafapo_t'] = df.loc[~df['cgo_eafapo_t']['art_kennz'].isin(['I1','I2','I3','I4']), 'cgo_eafapo_t']
  • Related