3

I created a text file called 'column.txt' containing the following data:

1
2
3
4
9
8

Then I wrote the code below to transpose my data to a single-row text file.

import numpy as np
x=np.loadtxt('column.txt')
z=x.T 
y=x.transpose()
np.savetxt('row.txt',y, fmt='%i') 

I tried two different ways - using matrix multiplication (the commented line in my code) and using transpose command. The problem was the output was exactly the same as the input!

Afterwards, I added another column to the input file, ran the code and surprisingly this time the output was completely fine (The output contained two rows!)

So my question is:

Is there anyway to transpose a single column file to a single row one? If yes, could you please describe how?

Armin
  • 331
  • 5
  • 11

3 Answers3

3

You can use numpy.reshape to transpose data and change the shape of your array like the following:

>>> import numpy as np
>>> arr=np.loadtxt('column.txt')
>>> arr
array([ 1.,  2.,  3.,  4.,  9.,  8.])
>>> arr.shape
(6,)
>>> arr=arr.reshape(6,1)
>>> arr
array([[ 1.],
       [ 2.],
       [ 3.],
       [ 4.],
       [ 9.],
       [ 8.]])

or you can just give the number of an array dimension as an input to the numpy.loadtxt function

>>> np.loadtxt('column.txt', ndmin=2)
array([[ 1.],
       [ 2.],
       [ 3.],
       [ 4.],
       [ 9.],
       [ 8.]])

But if you want to convert a single column to a single row and write it into a file just you need to do as following

>>> parr=arr.reshape(1,len(arr))
np.savetxt('column.txt',parr, fmt='%i')
Dalek
  • 4,168
  • 11
  • 48
  • 100
2

If your input data only consists of a single column, np.loadtxt() will return an one-dimensional array. Transposing basically means to reverse the order of the axes. For a one-dimensional array with only a single axis, this is a no-op. You can convert the array into a two-dimensional array in many different ways, and transposing will work as expected for the two-dimensional array, e.g.

x = np.atleast_2d(np.loadtxt('column.txt'))
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
1

It is because the transpose of a 1D array is the same as itself, as there is no other dimension to transpose to.

You could try adding a 2nd dimension by doing this,

>>> import numpy as np    
>>> x = np.array([[1], [2], [3], [4], [9], [8]])
>>> x.T
array([[1, 2, 3, 4, 9, 8]])
Pankaj Parashar
  • 9,762
  • 6
  • 35
  • 48