Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am working in python and am loading a text file that looks like this:

3    4

5    6

7    8

9    10

I use np.loadtxt('filename.txt') and it outputs an array like this:

([[3, 4]
  [5, 6]
  [7, 8]
  [9, 10]])

However, I want an array that looks like:

([3, 5, 7, 9], [4, 6, 8, 10])

Anyone know what I can do besides copying the array and reformatting it manually? I have tried a few things but they don't work.

share|improve this question
    
I think you're looking for numpy.transpose() –  Ben Jul 23 '14 at 20:07
    
Yes! Thank you, this works. –  Hannah Jul 23 '14 at 20:13

3 Answers 3

up vote 1 down vote accepted

Per my comment:

>>> x
array([[ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10]])
>>> numpy.transpose(x)
array([[ 3,  5,  7,  9],
       [ 4,  6,  8, 10]])
share|improve this answer

You can use the unpack option of np.loadtxt:

np.loadtxt('filename.txt', unpack=True) 

This will directly give you your array transposed. (http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html).

Another option is to use the transpose function for your numpy array:

your_array = np.loadtxt('filename.txt')
print(your_array)
([[3, 4]
 [5, 6]
 [7, 8]
 [9, 10]])

new_array = your_array.T
print(new_array)
([3, 5, 7, 9], [4, 6, 8, 10])

The transpose method will return you the transposed array, not transpose in place.

share|improve this answer

The best way to do this is to use the transpose method as follows:

import numpy as np

load_textdata = np.loadtxt('filename.txt')
data = np.transpose(load_textdata)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.