【问题标题】:Checking when more than one dataframe column has specific values in Python检查何时多个数据框列在 Python 中具有特定值
【发布时间】:2018-11-06 05:24:06
【问题描述】:

我的数据格式如下:

Shop              Date             Produced         Lost        Output     Signal
Cornerstop        01-01-2010          0              1            9          1
Cornerstop        01-01-2010          11             1            11         0
Cornerstop        01-01-2010          0              0            0          2
Cornerstop        01-01-2010          1              0            0          2
Cornerstop        01-01-2010          5              7            0          2
.
.
.
.

'Produced' 为 0 时,'Lost''Output' 的数据应该为 0,但那不是案子。我需要一种方法来找出何时不是这种情况(当 Produced 为 0 但 Lost、Output 或 Signal 中的任何一个都不为 0 时)。

制作一个计数器来计算这是真的与否的次数是我以前看到的数字:

counter = 0

for index, row in data.iterrows():
    if row['Produced'] and row['Lost'] != 0:
        counter += 1
    else:
        continue

我想确切地查看这些数据框中的哪些行(这是一个大集合),而且按每一行搜索几乎不是很有效。

有没有更好的方法可以做到这一点?

【问题讨论】:

    标签: python python-3.x pandas dataframe if-statement


    【解决方案1】:

    试试Boolean indexing:

    data[(data['Produced'] == 0) & (data['Lost'] != 0) & (data['Output'] != 0) & (data['Signal'] != 0)]
    

    【讨论】:

    • 谢谢。这是一种非常简单干净的方式。
    【解决方案2】:

    您可以使用布尔索引和pd.DataFrame.all。为了便于阅读,您可以将掩码存储在变量中:

    m1 = data['Produced'] == 0
    m2 = (data[['Lost', 'Output', 'Signal']] != 0).all(1)
    
    res = data[m1 & m2]
    

    【讨论】:

    • 我认为他们想要any:“...当 Produced 为 0 但 Lost、Output 或 Signal 中的任何一个都不为 0)。”
    • @SpghttCd,可能。但是接受的答案到处都有&,这意味着all。所以不完全确定。
    【解决方案3】:

    我的方法是布尔索引,其中一个数组用于==0 部分 (Produced) 和一个用于!=0 部分,通过locany 打包:

    df[df.Produced==0 & (df.loc[:, ['Lost', 'Output', 'Signal']]!=0).any(1)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-27
      • 2018-01-16
      • 2018-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      相关资源
      最近更新 更多