0

I have a set of integers and a set of numpy arrays, which I would like to use np.savetxt to store the corresponding integer and the array into the same row, and rows are separated by \n.

In the txt file, each row should look like the following:

12345678 0.282101 -0.343122 -0.19537 2.001613 1.034215 0.774909 0.369273 0.219483 1.526713 -1.637871 

The float numbers should separated by space

I try to use the following code to solve this

np.savetxt("a.txt", np.column_stack([ids, a]), newline="\n", delimiter=' ',fmt='%d %.06f')

But somehow I cannot figure out the correct formating for integer and floats.

Any suggestions?

1
  • Try setting multiple dtypes for you columns source Commented Nov 17, 2020 at 10:03

1 Answer 1

1

Please specify what a "set of integers" and "set of numpy arrays" are: from your example it looks as though ids is a list or 1d numpy array, and a is a 2d numpy array, but this is not clear from your question.

If you're trying to combine a list of integers with a 2d array, you should probably avoid np.savetxt and convert to a string first:

import numpy as np

ids = [1, 2, 3, 4, 5]
a = np.random.rand(5, 5)

with open("filename.txt", "w") as f:
    for each_id, row in zip(ids, a):
        line = "%d " %each_id + " ".join(format(x, "0.8f") for x in row) + "\n"
        f.write(line)

Gives the output in filename.txt:

1 0.38325380 0.80964789 0.83787527 0.83794886 0.93933360
2 0.44639702 0.91376799 0.34716179 0.60456704 0.27420285
3 0.59384528 0.12295988 0.28452126 0.23849965 0.08395266
4 0.05507753 0.26166780 0.83171085 0.17840250 0.66409724
5 0.11363045 0.40060894 0.90749637 0.17903019 0.15035594
Sign up to request clarification or add additional context in comments.

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.