Armin
Armin

Reputation: 361

Problems on how to transpose single column data in python

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?

Upvotes: 3

Views: 7120

Answers (3)

Dalek
Dalek

Reputation: 4318

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')

Upvotes: 3

Pankaj Parashar
Pankaj Parashar

Reputation: 10192

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]])

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 601489

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'))

Upvotes: 2

Related Questions