Uncategorized

How to convert a set of Python lists to numpy arrays?


I need to set the type of a set of arrays to be of the type np.ndarray each one. Since I need to do it multiple times, I’m trying a for loop, it seems to be correctly converting from list to np.ndarray when executing the loop, but once it ends, each of the arrays are still of list type, this block below helped me to realize that it is happening, but I have no idea why it is happening

So, why is this happening? and how to fix it? Thanks in advance

import numpy as np

pos = [1,1,1]
vel = [1,1,2]
# vel = np.array([1,1,2])
accel = [1,1,3]

print('\nredefining...')
for elem in [pos,vel,accel]:
    # checks if the array is of the np.ndarray class
    print(type(elem))
    if not isinstance(elem, np.ndarray):
        elem = np.array(elem)
        print(type(elem))
    print('---------------------------')

print('\nafter the redefinition:')

print(type(pos))
print(type(vel))
print(type(accel))

output:

redefining...
<class 'list'>
<class 'numpy.ndarray'>
---------------------------
<class 'list'>
<class 'numpy.ndarray'>
---------------------------
<class 'list'>
<class 'numpy.ndarray'>
---------------------------

after the redefinition:
<class 'list'>
<class 'list'>
<class 'list'>



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *