1

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 strings or ints in each cell, columns is a list of column names for mat, e.g. ['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.

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.