提问人:mins 提问时间:6/22/2023 更新时间:6/22/2023 访问量:52
向数组切片添加常量
Adding a constant to a slice of array
问:
尝试改变数组的切片,向具有奇数索引的元素添加常量。但这必须是一个副本,而不是分配的原始数组,因为这不会更改数组:
times = np.arange(10)
times[1::2] = times[1::2] + 0.5
这很好奇,因为它有效:
times[1::2] = -1
为什么切片是副本? 如何让它按预期工作?
答:
3赞
RomanPerekhrest
6/22/2023
#1
使用加法赋值(具有类型协议):
a = np.arange(10).astype(float)
a[1::2] += 0.5
array([0. , 1.5, 2. , 3.5, 4. , 5.5, 6. , 7.5, 8. , 9.5])
2赞
Learning is a mess
6/22/2023
#2
原因是添加将 dtype 从 int 更改为 float,当您尝试将其复制回切片 numpy 时,将通过将切片转换为副本而不是视图来解决 lhs 和 rhs 之间的 dtype 不兼容问题。0.5
times[1::2]
times[1::2] = times[1::2] + 0.5
检查
times = np.arange(10, dtype=float)
times[1::2] = times[1::2] + 0.5
#times = array([0. , 1.5, 2. , 3.5, 4. , 5.5, 6. , 7.5, 8. , 9.5])
将初始数组强制转换为 float 可以解除 dtype 不匹配,numpy 现在会切片到视图中,并且更改会传播回 中。times
有关详细信息,请参阅 https://numpy.org/doc/stable/user/basics.copies.html
评论
times[1::2] += .5
times[1::2] += .5
times[1::2] = times[1::2] + .5
x[....] = ...