2

I am in the process of trying to teach myself python so I am very new to this. My code is pretty simple. I just have a numpy array that I have randomly generated with integers. My code looks like this

arr = np.random.randint(100, size=(5,5))

print(arr)

When it prints it prints with brackets around it like this

[[98 87 45  5 67]
 [33 39  1 40 96]
 [97 55 85  2 65]
 [18 28 32 55 21]
 [96 46 14 87 28]]

How do I remove all of the brackets so it is only the numbers with the spaces between?

2
  • 2
    you can use re.sub to replace the brackets after converting the bumpy array to a string import re print(re.sub('[\[\]]', '', np.array_str(arr))) Commented Dec 19, 2019 at 6:01
  • 2
    I think you should learn to love those brackets :) They provide useful visual information. But as a programming learning task, it's mostly Python string handling. It's not much of a numpy task. Still it might be useful to look at the code for np.savetxt, and try to imitate that. Commented Dec 19, 2019 at 6:07

4 Answers 4

3

What about using Pandas?

import numpy as np
import pandas as pd

arr = np.random.randint(100, size=(5,5))
df = pd.DataFrame(arr)


print(df.to_string(header=False, index=False))

 45  40  99   8  20
 29  18  54  52  51
 94  52  84  61  17
 44  54  38  48  62
  4  76  95  73  46
Sign up to request clarification or add additional context in comments.

Comments

2

Try:

for el in arr:
     print(' '.join(el.astype(str)))

2 Comments

It returns an error TypeError: sequence item 0: expected str instance, numpy.int32 found
No worries, please consider upvoting, and mark this post as an answer to close it off
2

for example

import numpy as np
import re
arr = np.random.randint(100, size=(5,5))
print(arr)
print(re.sub('[\[\]]', '', np.array_str(arr)))

output:

[[71 35 79 89 85]
 [36 77 25 80 53] 
 [26 56  6 49 82]
 [27 84 18 86 62]
 [32 39 83 78 14]]

71 35 79 89 85
 36 77 25 80 53
 26 56  6 49 82
 27 84 18 86 62
 32 39 83 78 14

Comments

1
for i in arr:
    for j in i:
        print(j, end=' ')

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.