首页 > 解决方案 > 熊猫数据框上的多个条件

问题描述

我有一个要在数据集上运行以对大量数据进行排序的条件列表。

df = A Huge_dataframe. 例如。

  Index D1  D2  D3   D5      D6
    0   8   5   0  False   True
    1  45  35   0   True  False
    2  35  10   1  False   True
    3  40   5   2   True  False
    4  12  10   5  False  False
    5  18  15  13  False   True
    6  25  15   5   True  False
    7  35  10  11  False   True
    8  95  50   0  False  False

我必须根据给定的订单对 df 进行排序:

orders = [[A, B],[D, ~E, B], [~C, ~A], [~C, A]...] 
#(where A, B, C , D, E are the conditions) 

例如。

A = df['D1'].le(50)
B = df['D2'].ge(5)
C = df['D3'].ne(0)
D = df['D1'].ne(False)
E = df['D1'].ne(True)
# In the real scenario, I have 64 such conditions to be run on 5 million records. 

例如。我必须运行所有这些条件才能获得结果输出。

for loop完成以下任务的最简单方法是什么,使用or mapor对它们进行排序.apply

  df = df.loc[A & B]
  df = df.loc[D & ~E & B]
  df = df.loc[~C & ~A]
  df = df.loc[~C & A]

结果 df 将是我的预期输出。

multiple conditions在这里,我更感兴趣的是,如果我想运行存储在列表中的循环或映射或 .apply,您将如何使用它们。不是结果输出。

如:

for i in orders:
   df = df[all(i)] # I am not able to implement this logic for each order

标签: pandasmultiple-columnsmultiple-conditionslogical-and

解决方案


您正在寻找bitwise and里面的所有元素orders。在这种情况下:

df = df[np.concatenate(orders).all(0)]

推荐阅读