python - 如果满足 m 个条件中的任何 n 个,则为 Pandas

标签 python pandas

例子。

假设我有几列的数据框,我想选择匹配所有 4 个条件的行,我会写:

condition = (df['A'] < 10) & (df['B'] < 10) & (df['C'] < 10) & (df['D'] < 10)
df.loc[condition]

与此相反,如果我想选择与 4 个条件中的任何一个匹配的行,我会写:
condition = (df['A'] < 10) | (df['B'] < 10) | (df['C'] < 10) | (df['D'] < 10)
df.loc[condition]

现在,如果我想选择与这 4 个条件中的任意两个匹配的行怎么办?那将是匹配列(A 和 B)、(A 和 C)、(A 和 D)、(B 和 C)或(C 和 D)的任意组合的行。很明显,我可以用所有这些组合写出复杂的条件:
condition = ((df['A'] < 10) & (df['B'] < 10)) |\
            ((df['A'] < 10) & (df['C'] < 10)) |\
            ((df['A'] < 10) & (df['D'] < 10)) |\
            ((df['B'] < 10) & (df['C'] < 10)) |\
            ((df['C'] < 10) & (df['D'] < 10))
df.loc[condition]

但是如果有 50 列并且我想匹配这 50 列中的任何 20 列,那么将所有可能的组合列出到条件中就变得不可能了。有没有办法以某种方式更好地做到这一点?

最佳答案

True == 1False == 0您可以通过检查总和找到满足至少 N 个条件的行。系列具有大部分基本比较作为属性,因此您可以使用各种检查制作单个条件列表,然后使用 getattr使其整洁。

import pandas as pd
import numpy as np

np.random.seed(123)
df = pd.DataFrame(np.random.randint(0, 20, (5,4)), columns=list('ABCD'))
# can check `eq`, `lt`, `le`, `gt`, `ge`, `isin`
cond_list = [('A', 'lt', 10), ('B', 'ge', 10), ('D', 'eq', 4), 
             ('C', 'isin', [2, 4, 6])]
df_c = pd.concat([getattr(df[col], attr)(val).astype(int) 
                  for col,attr,val in cond_list], axis=1)
#   A  B  D  C
#0  0  0  0  1
#1  0  1  0  0
#2  1  1  0  0
#3  1  1  0  0
#4  0  1  0  1

# Each row satisfies this many conditions
df_c.sum(1)
#0    1
#1    1
#2    2
#3    2
#4    2
#dtype: int64

#Select those that satisfy at least 2.
df[df_c.sum(1).ge(2)]
#    A   B   C   D
#2   0  17  15   9
#3   0  14   0  15
#4  19  14   4   0

如果您需要一些更复杂的比较,而 .getattr 无法实现这些比较然后您可以自己写出它们并连接该系列列表。
df_c = pd.concat([df['A'].lt(10), df['B'].ge(10), df['D'].eq(4), 
                  df['C'].isin([2,4,6])], 
                 axis=1).astype(int)

关于python - 如果满足 m 个条件中的任何 n 个,则为 Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59867388/

相关文章:

python - 类型错误 : expected string or bytes-like object - how to copy files to an S3 bucket using the code provided in AWS's documentation

python - 选择性继承 Python

python - Spark SQL : TypeError ("StructType can not accept object in type %s" % type(obj))

python - Pandas :重命名具有相同名称的列

python - 返回两个行值之间的值(伪时间序列?)

python - Pandas:将多标题列的级别转入行索引

python - 通用协议(protocol) : mypy error: Argument 1 has incompatible type . ..;预期的

python - reshape Pandas 数据框将一行反转为多列

python - 将索引值设置为 date.time pandas 时遇到问题

python - 在python数据帧中的每列的最大值之前找到一个值的索引