numpy怎么遍历修改数组中的数据并保存为新的数组
时间: 2024-05-08 20:16:52 浏览: 10
可以使用numpy的迭代函数nditer()来遍历数组中的数据,修改数据后再保存为新的数组。
示例代码:
```python
import numpy as np
# 定义一个数组
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# 使用nditer()遍历数组并修改数据
new_arr = np.zeros(arr.shape)
it = np.nditer(arr, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
idx = it.multi_index
val = it[0]
new_val = val * 2 # 修改数据
new_arr[idx] = new_val # 保存修改后的数据到新的数组中
it.iternext()
print(arr)
print(new_arr)
```
输出结果:
```
[[1 2 3]
[4 5 6]
[7 8 9]]
[[ 2. 4. 6.]
[ 8. 10. 12.]
[14. 16. 18.]]
```
在上面的代码中,我们使用了nditer()函数来遍历数组arr中的每个元素。通过设置flags参数为'multi_index',我们可以获得每个元素的下标。同时,我们使用了op_flags参数将数组标记为可读写模式。在循环中,我们修改了每个元素的值,并将修改后的值保存到新的数组new_arr中。最终输出了原数组和修改后的新数组。