Home > Net >  How to properly swap numpy array
How to properly swap numpy array

Time:08-08

I am trying to swap the named columns of a numpy array as shown below, but the function is not behaving accordingly to what I anticipated. I see that the original 'data' is being changed even when I use the deepcopy from the copy module. Is there something that I am missing?

import copy
import numpy as np

data = np.array([(1.0, 2), (3.0, 4)], dtype=[('x', float), ('y',float)])

def rot(data, i):
    rotdata = copy.deepcopy(data)
    print(data['x'])
    if i == 0:
        pass
    if i == 1:
        rotdata['x'] = 5-rotdata['x']
    if i == 2:
        rotdata.dtype.names = ['y','x']
    if i == 3:
        rotdata.dtype.names = ['y','x']
        rotdata['x'] = 5-rotdata['x']
    if i == 4:
        rotdata['x'] = 5-rotdata['x']
        rotdata.dtype.names = ['y','x']
    if i == 5:
        rotdata['x'] = 5-rotdata['x']
        rotdata.dtype.names = ['y','x']
        rotdata['x'] = 5-rotdata['x']
    
    return rotdata

  

data1 = rot(data,5)
data2 = rot(data,5)
print(data1)
print(data2)

The result is,

[1. 3.]
[2. 4.]
[(4., 3.) (2., 1.)]
[(1., 2.) (3., 4.)]

Which is indeed against my intentions.

CodePudding user response:

Apparently copy.deepcopy() does not make a deep copy of the dtype object attached to the numpy array. So the data inside the array was copied, but you were switching names 'x' and 'y' in the data.dtype. So printing data['x'] gave you a different result, as did the second call data2 = rot(data,5).

You can solve it by adding the following line:

rotdata = copy.deepcopy(data)
rotdata.dtype = copy.deepcopy(data.dtype)
  • Related