我想在numpy数组的行上运行一个操作(例如减去中位数)。
一种方法是使用理解列表:
import numpy as np from statistics import median x = np.array([[1, 2, 3, 4], [5, 6, 7 ,8], [9, 10, 11, 12]]) xm = np.vstack(([x[i,:] - median(x[i,:]) for i in range(x.shape[0])]))处理每一行,然后垂直堆叠为numpy数组。
是否有更有效/更优雅的方式来做到这一点?
I would like to run an operation (e.g. subtracting the median) on rows of a numpy array.
One way to do that is using comprehension lists:
import numpy as np from statistics import median x = np.array([[1, 2, 3, 4], [5, 6, 7 ,8], [9, 10, 11, 12]]) xm = np.vstack(([x[i,:] - median(x[i,:]) for i in range(x.shape[0])]))Each row is processed, then stacked vertically as numpy array.
Is there a more efficient/elegant way to do that?
最满意答案
x - np.median(x, axis=1)[:, np.newaxis]给定np.median有一个keepdims参数,你也可以避免手动切片使其广播友好
x - np.median(x, axis=1, keepdims=True)如果你想逐行应用一个任意函数,比如statistics median ,你可以使用np.apply_along_axis ,只要注意它基本上是for循环所以你没有真正得到任何矢量化加速:
x - np.apply_along_axis(median, axis=1, x)[:,np.newaxis] x - np.median(x, axis=1)[:, np.newaxis]given np.median has a keepdims parameter you can also avoid the manual slicing to make it broadcasting-friendly
x - np.median(x, axis=1, keepdims=True)if you want to apply an arbitrary function row by row, like median from statistics, you can use np.apply_along_axis, just beware it's basically a for loop so you don't really get any vectorization speedup:
x - np.apply_along_axis(median, axis=1, x)[:,np.newaxis]更多推荐
发布评论