0

How can one rerange chararrays without getting a TypeError.

import numpy as np


    bggr =   ([['B', 'G', 'B', 'G'],
               ['G', 'R', 'G', 'R'],
               ['B', 'G', 'B', 'G'],
               ['G', 'R', 'G', 'R']])
    
    
    test = np.chararray((4, 4, 3)) #create empty chararray
    test[:] = ''
    test[::2, ::2, 2]=bggr[0::2, 0::2] #blue
    test[1::2, ::2, 1]=bggr[1::2, 0::2] #green
    test[::2, 1::2, 1]=bggr[0::2, 1::2] #green
    test[1::2, 1::2, 0]=bggr[1::2, 1::2] #red
    print(test)

Traceback (most recent call last):
  File "main.py", line 16, in <module>
    test[::2, ::2, 2]=bggr[0::2, 0::2] #blue
TypeError: list indices must be integers or slices, not tuple

Tried the exact same code with numbers instead of chars and it worked fine. Thank you.

  • The error says `bggr` is a list. You didn't do the same thing with numbers. That would have produced the same error - if the numbers were in a list! – hpaulj Nov 03 '22 at 15:19

1 Answers1

0

You need to use a numpy array for bggr:

import numpy as np


bggr = np.array([['B', 'G', 'B', 'G'],
                 ['G', 'R', 'G', 'R'],
                 ['B', 'G', 'B', 'G'],
                 ['G', 'R', 'G', 'R']])


test = np.chararray((4, 4, 3)) #create empty chararray
test[::2, ::2, 2]=bggr[0::2, 0::2] #blue
test[1::2, ::2, 1]=bggr[1::2, 0::2] #green
test[::2, 1::2, 1]=bggr[0::2, 1::2] #green
test[1::2, 1::2, 0]=bggr[1::2, 1::2] #red

print(test)

output:

[[['' '' b'B']
  ['' b'G' '']
  ['' '' b'B']
  ['' b'G' '']]

 [['' b'G' '']
  [b'R' b'\x04' '']
  ['' b'G' '']
  [b'R' '' '']]

 [[b'\x06' '' b'B']
  ['' b'G' '']
  ['' '' b'B']
  ['' b'G' '']]

 [['' b'G' '']
  [b'R' '' '']
  ['' b'G' '']
  [b'R' '' '']]]
mozway
  • 194,879
  • 13
  • 39
  • 75