Python:如何在矩阵/数据帧中从它前面的列中减去每n列?



基本上是寻找与这里发布的类似的解决方案,但随后在python中。R:如何在矩阵/数据帧中从它前面的列中减去每 n 列?

一些数据

import numpy as np
m = np.matrix([[1, 2, 3, 5], [3, 4, 5, 2], [5, 6, 7, 2]])

我想从之前的列值中减去每 2 列的值。所以我想以两列结束的解决方案。第一列中的每一行包含 -1,第二列包含 [-2, 3, 5]

提前感谢!

你可以做:

import numpy as np
m = np.matrix([[1, 2, 3, 5], [3, 4, 5, 2], [5, 6, 7, 2]])
a = m[:,0] - m[:,1]
b = m[:,2] - m[:,3]
m2 = np.concatenate((a, b), axis=1)
print(m2)

对于 n 列:

import numpy as np
m = np.matrix([[1, 2, 3, 5, 5 , 6], [3, 4, 5, 2, 3, 2], [5, 6, 7, 2, 7, 1]])
shape = np.shape(m)
print(shape)
result = []
if(shape[1] % 2 == 0):
for i in range(0, shape[1], 2):
print(i)
result.append(m[:,i] - m[:,i+1])
m2 = result[0]
for i in range(1, len(result)):
m2 = np.concatenate((m2, result[i]), axis=1)
print(m2)

最新更新