[英]How can I find a boolean index of a pandas data frame that matches a known subset of the data?
我有一个包含几列整数的数据框,比如说它们被标记为A
- E
。 我有兴趣根据A
、 B
和C
之间的关系找到D < E
的列。 我怀疑这种关系类似于D < E if (A < B) & (B > C)
。 我的目标是仅A
、 B
和C
来预测D < E
是否为真。
我也对理论方法感兴趣,我意识到这不属于 Python 问题,但我们将不胜感激。
You can mask the pandas dataframe with a boolean expression, and chek serveral things to evaluate the relatinship between A, B, C, D and E. My example is based on random number though. 但这应该给你方向。
import pandas as pd
import numpy as np
data = np.random.randint(0,10,(5,5))
df = pd.DataFrame(data, columns=["A", "B", "C", "D", "E"])
# filtering data on index value
mask = (df.D < df.E) & (df.A < df.B) & (df.B > df.C)
print(df)
# A B C D E
# 0 1 7 7 9 0
# 1 4 9 3 0 3
# 2 3 4 1 1 6
# 3 2 1 4 3 5
# 4 8 8 2 3 6
print(mask)
# 0 False
# 1 True
# 2 True
# 3 False
# 4 False
# dtype: bool
print(df[mask])
# A B C D E
# 1 4 9 3 0 3
# 2 3 4 1 1 6
print(len(df[mask].index))
# 2
print(mask.all())
# False
特别注意这一行:
mask = (df.D < df.E) & (df.A < df.B) & (df.B > df.C)
其中(df.D < df.E)
是D
和E
之间的关系, (df.A < df.B) & (df.B > df.C)
是A
、 B
和C
之间的关系。 如果两者都评估为True
,则关系“匹配”,最终结果将为True
。
我找到了一种使用operator
package 来迭代所有不等式关系组合的方法。 这是我使用的基本方法:
import itertools
from operator import *
for ineq1, ineq2, ineq3 in itertools.product([lt, le, ge, gt,
lambda a, b: True],
repeat=3):
mask = ineq1(data.A, data.B) & ineq2(data.B, data.C) & ineq3(data.C, data.A)
if data[mask].equals(taget_data):
print([ineq.__name__ for ineq in [ineq1, ineq2, ineq3])
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.