简体   繁体   中英

Changing shape of numpy array read from a text file

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM