1

I was trying to convert a big NumPy array to a string by using np.array_str() or str() but it turns out that the output does not contain all the values of the array.

weight=np.random.rand(5000,500)
print(weight.shape)
print(len(np.array_str(weight)))
print(len(str(weight)))
>>(5000,500)
>>443
>>443

Which is way less than the actual count of digits.

How can I get the complete array as a string? N.B. I want to write the sting in a text file.

1
  • How are you going to use this file later? Do you intend to read it and recreate the array? If so how? Practice on a small array before wasting time on a large one. Commented Jun 6, 2020 at 1:37

3 Answers 3

2

str(weight) is just the console representation of the string, it does not convert all values to string values, instead it generates a string that can be printed to the console, e.g.:

>>> str(weight)
'[[0.61063338 0.76216809 0.09732382 ... 0.74375515 0.09525192 0.43705637]\n [0.70583367 0.25657426 0.53279926 ... 0.72487029 0.36734946 0.67419836]\n [0.95006557 0.84218583 0.75602697 ... 0.51730571 0.11963987 0.84481707]\n ...\n [0.35017875 0.16172616 0.18016095 ... 0.74119508 0.09725982 0.93651959]\n [0.41584527 0.62796044 0.65794606 ... 0.12521724 0.62784847 0.57898542]\n [0.72758274 0.99773068 0.15162054 ... 0.42649996 0.631018   0.446582  ]]'

Try converting your array to a list and then to a string instead:

str(weight.tolist())
Sign up to request clarification or add additional context in comments.

Comments

1

To generate a tab- and line-separated representation (if you accept this), you can do

with open("test.txt", "w") as fh: weight.tofile(fh, sep="\t") 

Another way is to dump it as json, which is the same syntax as python code for a list:

from json import dump
with open("test.txt", "w") as fh: dump(weight.tolist(), fh)

I used json to make sure that nothing gets lost.

Comments

0

You can try:

conv_str = [[str(j) for j in i] for i in weight]

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.