基于多种功能从数据框中选择行

时间:2019-11-07 14:57:24

标签: python pandas

我有一个带有“ A”列的数据框df。如何根据多个条件选择df的子集。我正在尝试:

train.loc[(train["A"] != 2) or (train["A"] != 10)]

or运算符似乎不起作用。我怎样才能解决这个问题?我得到了错误:

ValueError                                Traceback (most recent call last)
<ipython-input-30-e949fa2bb478> in <module>
----> 1 sub_train.loc[(sub_train["primary_use"] != 2) or (sub_train["primary_use"] != 10), "year_built"]

/opt/conda/lib/python3.6/site-packages/pandas/core/generic.py in __nonzero__(self)
   1553             "The truth value of a {0} is ambiguous. "
   1554             "Use a.empty, a.bool(), a.item(), a.any() or a.all().".format(
-> 1555                 self.__class__.__name__
   1556             )
   1557         )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

2 个答案:

答案 0 :(得分:2)

|用于按位OR&用于按位AND,也不需要loc

#filter 2 or 10
train[(train["A"] == 2) | (train["A"] == 10)]
#filter not 2 and not 10
train[(train["A"] != 2) & (train["A"] != 10)]

如果还希望选择一些列,则有必要:

train.loc[(train["A"] == 2) | (train["A"] == 10), 'B']

答案 1 :(得分:2)

您需要|而不是OR来进行Series的逻辑:

train.loc[(train["A"] != 2) | (train["A"] != 10)]

不要担心括号,请使用Series.ne。 如果您不想选择特定的列,则loc原则上没有必要:

train[train["A"].ne(2) | train["A"].ne(10)]

但是我认为您的逻辑是错误的,因为此掩码未过滤 如果该值为2,则该值将不同于10,反之亦然,因此不会被过滤。我认为您想要Series.isin + ~

train[~train["A"].isin([2,10])]

&

train[train["A"].ne(2) & train["A"].ne(10)]