numpy数组上的高效行操作(Efficient row operation on numpy arrays)

编程入门 行业动态 更新时间:2024-10-25 18:32:21
numpy数组上的高效行操作(Efficient row operation on numpy arrays)

我想在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]

更多推荐

本文发布于:2023-08-03 09:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1385288.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:高效   数组   操作   numpy   arrays

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!