1

i have toy_df

toy_df = pd.DataFrame(['animal':['cat','cat','cat','dog']

   animal
0     cat
1     cat
2     cat
3     dog

i'm using toy_df_4 = toy_df[toy_df.animal == 'dog']

   animal
3     dog

how i can drop certain daaframe toy_df_4 from general toy_df

i have tried toy df - toy_df_4 but this error

TypeError: unsupported operand type(s) for -: 'str' and 'str'

this dataframes are toy so in real dataset i have dataframes with many conditions

3 Answers 3

3

Simpliest here is invert condition for get not matched rows by dog:

toy_df = pd.DataFrame({'animal':['cat','cat','cat','dog']})

toy_df_5 = toy_df[toy_df.animal != 'dog']
print (toy_df_5)
  animal
0    cat
1    cat
2    cat

But if really need drop by index value of filtered DataFrame:

toy_df_4 = toy_df[toy_df.animal == 'dog']
toy_df_5 = toy_df.drop(toy_df_4.index)
print (toy_df_5)
  animal
0    cat
1    cat
2    cat
Sign up to request clarification or add additional context in comments.

Comments

2
toy_df = pd.DataFrame({'animal':['cat','cat','cat','dog']})
toy_df4 = toy_df[toy_df.animal=='dog']

df = toy_df.merge(toy_df_4, how='outer', indicator=True).loc[lambda x: x['_merge']=='left_only'].reset_index(drop=True)
df = df.drop('_merge', axis=1)

output:

    animal
0    cat
1    cat
2    cat

Comments

1

Another approach is to use pandas.DataFrame.isin

toy_df = pd.DataFrame(['animal':['cat','cat','cat','dog']
toy_df_4 = toy_df[toy_df.animal == 'dog']
toy_df = toy_df[~toy_df.isin(toy_df_4)].dropna()

print(toy_df)
  animal
0    cat
1    cat
2    cat

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.