python numpy数组中的元组减法

dauxcl2d  于 2023-06-04  发布在  Python
关注(0)|答案(1)|浏览(167)

我有一个n维数组,其中元组作为元素。我想从数组中减去一个元组并返回一个数组。

  1. import numpy as np
  2. x=5
  3. y=5
  4. z=3
  5. # Create an empty array of size 10x8x4
  6. array_slots = np.empty((x, y, z), dtype=object)
  7. array_slots_end = np.empty((x, y, z), dtype=object)
  8. # Iterate over the indices and assign tuples
  9. for i in range(x):
  10. for j in range(y):
  11. for k in range(z):
  12. array_slots[i, j, k] = (i, j, k)

从上面的数组创建另一个数组

  1. filtered_array = np.concatenate((array_slots[0,:,:],array_slots[:,0,:]),axis=0)
  2. # Filtered_away method creates duplicate entries, hence dropping them.
  3. array_slots_end = DataFrame(filtered_array).drop_duplicates().values

最后试着做一个减法:

  1. np.subtract(array_slots[0],array_slots_end[0,0])
  2. TypeError: unsupported operand type(s) for -: 'tuple' and 'int'

但是,当我直接运行数组时,它可以工作。这就是我想要的输出。

  1. np.subtract([[(0, 0, 0), (0, 0, 1), (0, 0, 2)],
  2. [(0, 1, 0), (0, 1, 1), (0, 1, 2)],
  3. [(0, 2, 0), (0, 2, 1), (0, 2, 2)],
  4. [(0, 3, 0), (0, 3, 1), (0, 3, 2)],
  5. [(0, 4, 0), (0, 4, 1), (0, 4, 2)]],(0, 0, 0))
  6. array([[[0, 0, 0],
  7. [0, 0, 1],
  8. [0, 0, 2]],
  9. [[0, 1, 0],
  10. [0, 1, 1],
  11. [0, 1, 2]],
  12. [[0, 2, 0],
  13. [0, 2, 1],
  14. [0, 2, 2]],
  15. [[0, 3, 0],
  16. [0, 3, 1],
  17. [0, 3, 2]],
  18. [[0, 4, 0],
  19. [0, 4, 1],
  20. [0, 4, 2]]])

我做错了什么?

5ktev3wc

5ktev3wc1#

在'direct'的情况下,您提供的是一个列表,而不是一个数组

  1. np.subtract([[(0, 0, 0), (0, 0, 1), (0, 0, 2)],
  2. [(0, 1, 0), (0, 1, 1), (0, 1, 2)],
  3. [(0, 2, 0), (0, 2, 1), (0, 2, 2)],
  4. [(0, 3, 0), (0, 3, 1), (0, 3, 2)],
  5. [(0, 4, 0), (0, 4, 1), (0, 4, 2)]],(0, 0, 0))

np.subtract使两个参数都成为数组,然后执行减法
看看你用列表的np.array得到了什么

  1. In [52]: np.array([[(0, 0, 0), (0, 0, 1), (0, 0, 2)],
  2. ...: [(0, 1, 0), (0, 1, 1), (0, 1, 2)],
  3. ...: [(0, 2, 0), (0, 2, 1), (0, 2, 2)],
  4. ...: [(0, 3, 0), (0, 3, 1), (0, 3, 2)],
  5. ...: [(0, 4, 0), (0, 4, 1), (0, 4, 2)]]).shape
  6. Out[52]: (5, 3, 3)

这是一个3d int dtype数组,不是你的对象dtype与元组。
这很好地说明了为什么,至少对于计算目的来说,数字数组是最好的。
它不能在元组上做数学运算。元组是python对象,就像列表一样,只能做加法,定义为join,乘法,复制。这是基本的Python。
要创建元组数组,您必须使用一个非常迂回的方法,创建None数组,并使用一个新的元组对象分别填充每个元素。操作这些元组同样是乏味的。

  1. In [53]: np.array([[(0, 0, 0), (0, 0, 1), (0, 0, 2)],
  2. ...: [(0, 1, 0), (0, 1, 1), (0, 1, 2)],
  3. ...: [(0, 2, 0), (0, 2, 1), (0, 2, 2)],
  4. ...: [(0, 3, 0), (0, 3, 1), (0, 3, 2)],
  5. ...: [(0, 4, 0), (0, 4, 1), (0, 4, 2)]])
  6. Out[53]:
  7. array([[[0, 0, 0],
  8. [0, 0, 1],
  9. [0, 0, 2]],
  10. [[0, 1, 0],
  11. [0, 1, 1],
  12. [0, 1, 2]],
  13. [[0, 2, 0],
  14. [0, 2, 1],
  15. [0, 2, 2]],
  16. [[0, 3, 0],
  17. [0, 3, 1],
  18. [0, 3, 2]],
  19. [[0, 4, 0],
  20. [0, 4, 1],
  21. [0, 4, 2]]])
展开查看全部

相关问题