![]() |
Numpy error while filling up matrix with Characters - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Numpy error while filling up matrix with Characters (/thread-36935.html) |
Numpy error while filling up matrix with Characters - august - Apr-13-2022 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 RE: Numpy error while filling up matrix with Characters - deanhystad - Apr-13-2022 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)
RE: Numpy error while filling up matrix with Characters - august - Apr-13-2022 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 RE: Numpy error while filling up matrix with Characters - deanhystad - Apr-13-2022 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. RE: Numpy error while filling up matrix with Characters - august - Apr-13-2022 Thanks. Later on I want to make a plot with colors depending on the letters, thats why I'm trying to use numpy |