我有toy_df
toy_df = pd.DataFrame(['animal':['cat','cat','cat','dog']
animal
0 cat
1 cat
2 cat
3 dog
我正在使用toy_df_4 = toy_df[toy_df.animal == 'dog']
animal
3 dog
我如何从通用toy_df_4
删除某些daaframe toy_df
我尝试了toy df - toy_df_4
,但此错误
TypeError: unsupported operand type(s) for -: 'str' and 'str'
此数据框是玩具,因此在实际数据集中,我具有许多条件的数据框
答案 0 :(得分:3)
这里最简单的是用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
但是如果确实需要按过滤后的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
答案 1 :(得分:1)
另一种方法是使用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
答案 2 :(得分:1)
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)
输出:
animal
0 cat
1 cat
2 cat