使用多个条件选择行

Selection of rows using multiple criteria

我想通过使用多个布尔 selection 条件从数据框中删除某些行。这是我的测试数据框:

import pandas as pd

df = pd.DataFrame({'a':range(0,10,2), 'b':range(0,1000,200)})
df['c'] = 10*df.b
df

我可以 select 我想删除的行,使用这些单独的命令:

df1 = df.ix[df.c>5000]
df2 = df1.ix[df1.b<800]
df2

留给我由一行组成的 df2:

我希望能够 select 使用一行可能看起来像这样的行:

df2 = (df.ix[df.c>5000]) & (df.ix[df1.b<800])
df2

但这不起作用。最后,当然我想把它变成一个删除命令。

为了根据您尝试在描述中应用的条件进行选择,请尝试使用布尔索引:

>> condition = (df.c > 5000) & (df.b < 800)
>> df2 = df[condition]

为了删除,使用相同的条件,你可以这样做:

>> df.drop(df[condition].index.tolist())

这将 return 一个 pd.core.frame.DataFrame,您需要在此处分配或使用 inplace 标志,如下所示:

>> df.drop(df[condition].index.tolist(), inplace=True)

希望对您有所帮助!

如果您想删除行而不是保留它,您可以使用 ~ 运算符反转布尔向量。

df2 = df[~((df.c > 5000) & (df.b < 800))]

您可以通过

获取要删除的索引
indices = df[(df.c > 5000) & (df.b < 800)].index

并删除它们(就地):

df.drop(indices, inplace=True)

如果你也想重置索引,那么

df = df.drop(indices).reset_index(drop=True)