python - numpy中的二元运算

标签 python numpy

我有一个看起来像这样的数组,

array([[[-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    ..., 
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024]],

   [[-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    ..., 
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024]],

   [[-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    ..., 
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024]],

   ..., 
   [[-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],

它是一个包含许多独特元素的冗长数组,我该如何执行操作,如果值大于 100,则将值设置为 1,否则将所有值设置为 0。

我试过了

resulted  = np.array([0 if x < 100 else 1 for x in new_one])

但是我明白了,

ValueError Traceback (most recent call last) in () ----> 1 resulted = np.array([0 if x < 100 else 1 for x in new_one])

<ipython-input-72-77697094b8bd> in <listcomp>(.0)
----> 1 resulted  = np.array([0 if x < 100 else 1 for x in new_one])

ValueError: The truth value of an array with more than one element is        ambiguous. Use a.any() or a.all()

关于我如何推进这项工作有什么想法吗?提前致谢。

最佳答案

Astype int of boolean 会给你想要的,即

arr = np.array([[[-1024, -1024, -1024, 0, -1024, -1024, -1024],
[-1024, -1024, -1024, 150, -1024, -1024, -1024],
[-1024, -1024, -1024,300, -1024, -1024, -1024]]])


(arr>100).astype(int)

array([[[0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0]]])

关于python - numpy中的二元运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48079856/

相关文章:

Python:迭代器返回无

python - 使用 Tkinter 在未知长度的可迭代中为每个项目创建一个条目

python - 我如何使用附加属性扩展我的 2 个暗淡 numpy 数组

python - 值错误 : negative dimensions are not allowed using pandas pivot_table

python - 如何按列获取重复数字的长度?

python-3.x - Python - 从 URL 读取图像以调整图像大小并将图像转换为灰度

javascript - 处理多个 setinterval javascript

python - Orange PCA 和 scikit-learn PCA 的结果不同

python - 如何发送电子邮件附件?

python - 如何确定 numpy.datetime64 中的时间单位?