简体   繁体   中英

Concatenate strings from a 2D numpy array

I want to concatenate a string from a 2d numpy array like this,

for x in np.ndindex(mat.shape[0]):
    concat = ""
    for y in range(len(columns)):
        concat += str(mat[x][2 + y])

where mat is a 2d array containing string s or int s in each cell, columns is a list of column names for mat , eg ['A', 'B', 'C', 'D'] , using mat[x][2 + y] to avoid concatenating strings from the 1st two columns. I am wondering what is the best way to do it, probably in a more concise/efficient way.

You have been a little vague in your definition of concatenate — I hope that the following is enough to get you started

print('\n'.join(' '.join(str(x) for x in row[2:]) for row in mat))

The external join joins the rows with a newline, the internal one joins a few of the elements of each row in mat — if you are not after ALL the elements except the first two, modify to please you the upper limit of the slice...

Note that str(x) leaves string elements undisturbed and formats numeric items in a reasonable way.

Ab -using the fact that we are dealing with a 2D array, we can resort to just one loop -

["".join(i) for i in mat[:,2:].astype(str)]

Sample run -

In [143]: mat
Out[143]: 
array([[1, 1, 0, 3, 1, 1],
       [3, 0, 1, 1, 1, 0],
       [2, 2, 1, 2, 1, 1]])

In [144]: ["".join(i) for i in mat[:,2:].astype(str)]
Out[144]: ['0311', '1110', '1211']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM