11

I know how to use numpy.savetxt to write an array to a file. How can I write multiple arrays to the same file?

Essentially I want to do math to a column of numbers, and then replace the old column with the modified numbers. I read the easiest way to do this is to write a new file completely, put the modified numbers in, and just 'copy and paste' the other numbers in the file.

Any help is appreciated.

Thanks!

3 Answers 3

8

Answering a very old post for my own use. I've used the following to write out two 1D arrays of same size as CSV.

import numpy as np

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
# >>> [(1, 4), (2, 5), (3, 6)]

# Save the array back to the file
np.savetxt('z.csv', zipped, fmt='%i,%i')
Sign up to request clarification or add additional context in comments.

1 Comment

This seems nice, but does not work on Python 3. Here, an IndexError is thrown by NumPy.
6

If you're wanting to write multiple arrays to a file for later use, Look into numpy.savez.

However, from your description, it sounds like you're wanting to do something with a particular column of a delimited text file.

In that case, just load the entire thing in and operate on just the column you need to.

E.g.

import numpy as np

data = np.loadtxt('test.txt')

# Multiply the 4th column by 5
data[:,3] *= 5

# Do something more complicated to the 2nd column
data[:,1] = np.cos(data[:,1])

# Save the array back to the file
np.savetxt('test.txt', data)

Comments

1
import numpy


list1 = [1, 2, 3, 4]

list2 = [0.45, 0.98, 0.89, 0.21]

dat = numpy.array([list1, list2])

dat = dat.T

numpy.savetxt('data.txt', dat, delimiter = ',')

2 Comments

Welcome to StackOverflow and thanks for trying to help. Please explain your code-only answer.
Doesn't work: get Mismatch between array dtype ('object') and format specifier ('%.18e')

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.