我需要(n,3)数组第一列中每个元素的x2 - x1
n 倍差,以便产生(n,n)数组。意思是,我需要:
[0,0] - [0,0], [1,0] - [0,0], [2,0] - [0,0],...[n,0] - [0,0]
[0,0] - [1,0], [1,0] - [1,0], [2,0] - [1,0],...[n,0] - [0,0]
:
[0,0] - [n,0], [1,0] - [n,0], [2,0] - [n,0],...[n,0] - [n,0]
我尝试过numpy.diff(a[:,0])
,尽管这只会产生直接相邻元素之间的差异,即[1,0] - [0,0], [2,0] - [1,0],...[n,0] - [n-1,0]
。
答案 0 :(得分:1)
对于此类问题,绝对不要使用三个嵌套的for循环。
说实话,我不太了解您的最终目标,但是IIUC,您可以使用广播
application/something+json
产生
(a - a[:, None])[..., 0]
如果要对第二列执行相同的操作,只需使用array([[ 0, -2, 3],
[ 2, 0, 5],
[-3, -5, 0]])
等。
如果仅在第一列中真正需要此操作(而在其他列中则不需要),那么计算所有内容然后提取第一个结果可能会过大。您可能会先切片,然后使用广播减去
[..., 1]
答案 1 :(得分:-1)
因此,问题的表述有点令人困惑,将示例包含在原始问题的注释中以及更好的数学表述将是一件很不错的事。
您也许可以使用numpy
来做到这一点,但是它看起来是如此具体,以至于我坚持只使用list
来代替。这是使用注释示例的方法:
import numpy as np
ex = [
[5, 2, 4],
[3, 9, 8],
[8, 3, 7]
]
ex_as_np_array = np.array(ex)
rows, cols = ex_as_np_array.shape[0], ex_as_np_array.shape[1]
# Forcing in order to only get the results for the first column
# Otherwise the result is going to be (9, 3) or (nrows*ncols, nrows).
cols = 1
result = []
for row in range(0, rows):
for col in range(0, cols):
row_result = []
for i in range(0, rows):
operation = ex[i][col] - ex[row][col]
row_result.append(operation)
result.append(row_result)
result_as_np_array = np.array(result)
哪个给:
Result:
[[ 0 -2 3]
[ 2 0 5]
[-3 -5 0]]
Shape:
(3, 3)