我有一个数据框(df),其中包含具有实际测量值的几列以及相应数量的列(A,B,...),其中每列具有不确定性(dA,dB,...):
A B dA dB
0 -1 3 0.31 0.08
1 2 -4 0.263 0.357
2 5 5 0.382 0.397
3 -4 -0.5 0.33 0.115
我应用一个函数来查找测量列中根据我的定义有效的值
df[["A","B"]].apply(lambda x: x.abs()-5*df['d'+x.name] > 0)
这将返回一个布尔数组:
A B
0 False True
1 True True
2 True True
3 True False
我想使用这个数组来选择数据框中单列中条件为真的行,例如A-> 行1-3,并且还查找所有输入列的条件都为 true 的行,例如排1 and 2。
有没有一种有效的方法可以用熊猫来做到这一点?
您可以使用 apply 语句的结果来从原始数据帧中选择布尔索引:
results = df[["A","B"]].apply(lambda x: x.abs()-5*df['d'+x.name] > 0)
它返回上面的布尔数组:
A B
0 False True
1 True True
2 True True
3 True False
现在,您可以使用此数组从原始数据框中选择行,如下所示:
选择 A 为 True 的情况:
df[results.A]
A B dA dB
1 2 -4.0 0.263 0.357
2 5 5.0 0.382 0.397
3 -4 -0.5 0.330 0.115
选择 A 或 B 为 true 的情况:
df[results.any(axis=1)]
A B dA dB
0 -1 3.0 0.310 0.080
1 2 -4.0 0.263 0.357
2 5 5.0 0.382 0.397
3 -4 -0.5 0.330 0.115
选择所有列都为 true 的位置:
df[results.all(axis=1)]
A B dA dB
1 2 -4.0 0.263 0.357
2 5 5.0 0.382 0.397
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)