python - Python:将两个数组作为函数参数传递。期待一个系列,但只返回最后一个值
问题描述
我相信还有其他方法可以做到这一点,但我想知道为什么我会得到我得到的结果。
为了增加上下文,我正在尝试在 python 中学习向量化,并且遇到了显示传递数组比说 .apply() 方法更快的教程。
目的:比较两个布尔数组,并根据多个条件,返回一个也应该是一个系列的结果。
但是,执行以下操作时,我只得到最后一个组合的值,而不是一系列结果。
bool_1 = np.array([True,False,False])
bool_2 = np.array([False,True,False])
# Categorise the outcomes
def bool_combinations(bool_array_1,bool_array_2):
if bool_array_1 is True:
OUTCOME = "Outcome 1"
elif bool_array_2 is True:
OUTCOME = "Outcome 2"
else:
OUTCOME = "Outcome 3"
print(bool_array_1,bool_array_2,OUTCOME)
return OUTCOME
bool_combinations(bool_1,bool_2)
从上面我得到的输出:
[ True False False] [False True False] Outcome 3
'Outcome 3'
我希望得到一个看起来更像的结果:
[ True False False] [False True False] [ 'Outcome 1' 'Outcome 2' 'Outcome 3']
[ 'Outcome 1' 'Outcome 2' 'Outcome 3']
解决方案
您很接近,但您可能希望将数组压缩在一起并逐个元素进行比较,而不是比较数组的真实性。您获得“成果 3”的原因是:
numpy.array([...]) is True ## ---> is always False
使用您的代码作为基础,您可以尝试:
import numpy
def bool_combinations(bool_array_1,bool_array_2):
OUTCOME = []
for (bool1, bool2) in zip(bool_array_1,bool_array_2):
if bool1:
OUTCOME.append("Outcome 1")
elif bool2:
OUTCOME.append("Outcome 2")
else:
OUTCOME.append("Outcome 3")
return OUTCOME
bool_1 = numpy.array([True,False,False])
bool_2 = numpy.array([False,True,False])
print(bool_combinations(bool_1,bool_2))
这会给你:
['Outcome 1', 'Outcome 2', 'Outcome 3']
我个人可能会这样做:
import numpy
def bool_combinations(bool_array_1,bool_array_2):
def _get_outcome(bool1, bool2):
if bool1: return "Outcome 1"
if bool2: return "Outcome 2"
return "Outcome 3"
return [_get_outcome(bool1, bool2) for bool1, bool2 in zip(bool_array_1,bool_array_2)]
bool_1 = numpy.array([True,False,False])
bool_2 = numpy.array([False,True,False])
print(bool_combinations(bool_1,bool_2))
这也会给你:
['Outcome 1', 'Outcome 2', 'Outcome 3']
您仍然可以变得更高尔夫球,但我认为缩短它不会导致代码更容易理解。
推荐阅读
- json - apache nifi - 按字段值分割 json 行
- java - 包“com.example”从“javafx.base”和“javafx.base”中读取包“javafx.beans”
- postgresql - Postgresql 不使用 GIN 索引来表示“?” JSON 运算符
- java - 如何制作继承对象的数组 - Java
- c++ - 我应该如何将模板化函数存储在任何容器中?
- php - 将数组的值相加 N 次以达到目标
- c++ - OpenProcess() Access_Denied 与 SeDebugPrivilege
- php - 无法获取类别产品 Woocommerce
- python - format=None 在 Django rest full API 中有什么作用
- typescript - 我们如何将字符串数组映射到类型键的 TypeScript 类型映射?