Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 346
Armin Avatar asked Sep 10 '26 11:09

Armin


2 Answers

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')
like image 119
Dalek Avatar answered Sep 12 '26 23:09

Dalek


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'))
like image 36
Sven Marnach Avatar answered Sep 12 '26 23:09

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!