如何用numpy重塑这个数组?

时间:2016-03-02 20:37:33

标签: python numpy

我的文件看起来像这样

3.766204987418e+00  3.016098278453e+00  2.882128625608e+00  2.789447648712e+00  2.704276250639e+00 
 2.540138572067e+00  2.318587560199e+00  2.272640952350e+00  2.138794921589e+00 

我还有代码来阅读它

import numpy as np

zxyr=[]

with open('det.txt') as f:
    zxyr=list(f)

c=np.asarray(zxyr)
print c.shape
print len(c)

产生

(2,)
2

如何将数组重塑为(9,)形状?

EDIT 我试过了

import numpy as np      

c = np.loadtxt('det.txt')
print (c.shape)

Traceback (most recent call last):
  File "kiev.py", line 3, in <module>
    c = np.loadtxt('det.txt')
  File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 856, in loadtxt
    X = np.array(X, dtype)
ValueError: setting an array element with a sequence.

1 个答案:

答案 0 :(得分:0)

As @ B.M.在评论中说你需要使用np.loadtxt。如下图所示:

import numpy as np      

c = np.loadtxt('mytextfile.txt)
print (c.shape)

这将从文件中获取数据并将其放入numpy数组中。 如果我的示例中的文本文件与您的文本文件相同,那么它将具有您需要的形状(9,)

您可以采取的另一种方法如下:

with open('mytextfile.txt') as f:
    content = f.readlines()