【问题标题】:Choosing rows from a dataframe based on multiple functions [duplicate]基于多个函数从数据框中选择行[重复]
【发布时间】:2020-03-04 04:37:35
【问题描述】:

我有一个带有“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().

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用| 表示按位OR&amp; 表示按位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']
    

    【讨论】:

    • 这个面具不会过滤任何东西。我想他想要&amp;..
    【解决方案2】:

    你需要 | 而不是 OR 来对 Series 进行逻辑处理:

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

    不用担心括号,请使用Series.neloc这里如果不想选择特定列原则上是不需要的:

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

    但我认为你的逻辑是错误的,因为这个面具没有过滤 如果值为 2,则不会被过滤,因为它与 10 不同,反之亦然。我想你想要Series.isin + ~:

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

    &amp;

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

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 1970-01-01
      相关资源
      最近更新 更多