Stack multiple columns in a text file

Viewed 84

I'm trying to save a txt file in Python through numpy.savetxt. The data should be organized in columns that I read from a 2 dimensional list: basically I need to write

np.column_stack((noise[:,0], noise[:,1], ..., noise[49]))

In the end 50 columns should be present.

Is there any way to avoid writing this manually and do it automatically instead (maybe even for a different number of columns)?

2 Answers

How about list or generator comprehension?

np.column_stack((noise[:, idx] for idx in range(50)))
np.column_stack(tuple(noise[:, idx] for idx in range(50)))
np.column_stack([noise[:, idx] for idx in range(50)])

You can simply transform the 2D list into a numpy array and then save it.

Example:

import numpy as np
X = [['A', 'A'], ['B', 'B']]
X = np.array(X)
np.savetxt('test.out', X, delimiter=',')
Related