1

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.

1
  • I think you're looking for numpy.transpose() Commented Jul 23, 2014 at 20:07

3 Answers 3

1

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]])
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.