python np array 减去一个数_从多维Numpy数组中减去均值

I'm currently learning about broadcasting in Numpy and in the book I'm reading (Python for Data Analysis by Wes McKinney the author has mentioned the following example to "demean" a two-dimensional array:

import numpy as np

arr = np.random.randn(4, 3)

print(arr.mean(0))

demeaned = arr - arr.mean(0)

print(demeaned)

print(demeand.mean(0))

Which effectively causes the array demeaned to have a mean of 0.

我的想法是将其应用于类似图像的三维数组:

import numpy as np

arr = np.random.randint(0, 256, (400,400,3))

demeaned = arr - arr.mean(2)

当然哪个失败了,因为根据广播规则,尾随尺寸必须匹配,在这里不是这种情况:

print(arr.shape) # (400, 400, 3)

print(arr.mean(2).shape) # (400, 400)

现在,通过从数组第三维中的每个索引中减去均值,我已经使其大部分工作了:

demeaned = np.ones(arr.shape)

for i in range(3):

demeaned[...,i] = arr[...,i] - means

print(demeaned.mean(0))

此时,返回值非常接近零,我认为这是一个精度误差。我真的对这个想法正确,还是我想念了另一个警告?

Also, this doesn't seam to be the cleanest, most 'numpy'-way to achieve what i wanted to achieve. Is there a function or a principle that i can make use of to improve the code?

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值