Home > Software design >  Converting long 2D list to NumPy array dosn't convert the lists inside
Converting long 2D list to NumPy array dosn't convert the lists inside

Time:05-28

I wanted to convert my long python 2D list to a NumPy 2D array, but after converting the lists inside the list still stayed as vanila lists:

import numpy as np

# The list should be longer, but this long is enogh to state the problem
# And please don't ask why is it about zombies
list = [['<sup>4</sup>;{{P|Mummy Zombie|2}}'], 
        ['<sup>2</sup>;{{P|Ra Zombie|2}}'],
        ['<sup>4</sup>;{{P|Mummy Zombie|2}}', '<sup>5</sup>;{{P|Mummy Zombie|2}}']]

np.array(list)

list
>>> [list(['<sup>4</sup>;{{P|Mummy Zombie|2}}'])
     list(['<sup>2</sup>;{{P|Ra Zombie|2}}'])
     list(['<sup>4</sup>;{{P|Mummy Zombie|2}}', '<sup>5</sup>;{{P|Mummy Zombie|2}}'])]

What i've expected:

list = [['1', '7', '0'], ['6', '2', '5'], ['7', '8', '9'], ['41', '10', '20']]

np.array(list)

list
>>>[['1' '7' '0']
    ['6' '2' '5']
    ['7' '8' '9']
    ['41' '10' '20']]

Is there some fix to this problem? Or should I report this as a bug to NumPy?

CodePudding user response:

Firstly, you use list as variable name. It is a built-in type. For that reason, you should not use it.

After that, your list array includes 1,1,2 element respectively by row. The column number of each row should be equal to each other.

list2 = [['<sup>4</sup>;{{P|Mummy Zombie|2}}'], 
    ['<sup>2</sup>;{{P|Ra Zombie|2}}'],
    ['<sup>4</sup>;{{P|Mummy Zombie|2}}'], 
    ['<sup>5</sup>;{{P|Mummy Zombie|2}}']]

np.array(list2)
>>> array([['<sup>4</sup>;{{P|Mummy Zombie|2}}'],
   ['<sup>2</sup>;{{P|Ra Zombie|2}}'],
   ['<sup>4</sup>;{{P|Mummy Zombie|2}}'],
   ['<sup>5</sup>;{{P|Mummy Zombie|2}}']], dtype='<U33')


np.array(list2).shape
>>>(4, 1)
  • Related