Python Forum

Full Version: Numpy error while filling up matrix with Characters
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm new to numpy. I've a string of characters. I'm truncating it one character at a time till only one character is left.
Then I'm trying to fill up a numpy array with these individual substrings in a column wise fashion.

import numpy as np
mystr = 'ASDFL'
bs = [mystr[:x+1] for x in range( len( mystr)) ]
bs = sorted(bs, key=len, reverse=True )
fm = np.empty(shape=( len(mystr), len(bs) ), dtype='str')
for j in range(len(bs)):
    fm[:, j] = list(bs[j])
However I'm getting the following error:
"ValueError: cannot copy sequence with size 4 to array axis with dimension 5"

Can anybody help me solve this problem? Thanks
Why are you using numpy? Do you need a 5x5 array for some reason?

Is this what you are looking for?
import numpy as np
mystr = 'ASDFL'
n = len(mystr)
bs = [mystr[:x] for x in range(n, 0, -1)]
fs = np.empty((n, n), dtype=str)
for index, values in enumerate(bs):
    fs[index,:len(values)] = list(values)
print(fs)
Output:
[['A' 'S' 'D' 'F' 'L'] ['A' 'S' 'D' 'F' ''] ['A' 'S' 'D' '' ''] ['A' 'S' '' '' ''] ['A' '' '' '' '']]
Hello deanhystad,
Thank you very much. Actually this is a part of the problem. I've to do this for many string like ASDFL, QWERTY etc and sub-strings can start from any place inside the string , hence it would be n X m matrix. If possible can you point out where I was going wrong?
was it in the declaration of the array ?
fm = np.empty(shape=( len(mystr), len(bs) ), dtype='str')
Or
fm[:, j] = list(bs[j]
or somewhere else?

Thanks again
You cannot use ":" by itself unless len(bs[j]) == len(fm[:,j]. You could do like I did and copy bs[j] to a slice in f[], or you can pad everything in bs[] to be the same length, or you can copy characters over one at a time. Your choice.

You didn't answer the question about why you are using numpy. This would be simple if you could have a list of lists.
Thanks. Later on I want to make a plot with colors depending on the letters, thats why I'm trying to use numpy