问题描述:

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.

网友答案:

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]])
网友答案:

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.

网友答案:

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)
相关阅读:
Top