我有一个文本文件,其中包含大量行。每行有4096个整数值。
500 501 300 400 ------------------------------------------------------------
300 400 600 700 -----
501 407 603 771 ------------------------------------------------------------
382 659 889 700 -----
so on
我想做的是使用numpy将文件作为一维数组读取。我无法使用简单的loadtxt来完成此操作,因为它需要相同数量的列。 有什么建议我该怎么做?我的最终目标是操纵该数组以插入某些值。
您可以在此处从我的代码中获取更多详细信息,
from sys import argv
import numpy as np
script, PhilFile = argv
intxt = open(PhilFile)
invalues = intxt.read()
invalues = invalues.replace(' ', '\n')
adc = np.asarray(invalues)
print adc
N_CHANS = 5
N_SAMPS = 256
H = len(adc)/N_SAMPS
N = 0
header = np.array([666,777,888,999])
for l in range(0,H) :
adc = np.insert(adc, [N]*header.size, header)
N += 258
print adc
np.savetxt("test1.txt", adc)
我提供文本文件作为参数,目前,我得到一个错误,
H = len(adc)/N_SAMPS
TypeError: len() of unsized object
答案 0 :(得分:0)
我可以通过以下方式重现您的错误:
In [596]: np.array('1 2 3 4 5')
Out[596]: array('1 2 3 4 5', dtype='<U9')
In [597]: len(_)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-597-556fcc1c5d2a> in <module>()
----> 1 len(_)
TypeError: len() of unsized object
从单个字符串构造一个数组将生成一个0d单元素数组。
您必须首先分割字符串:
In [598]: np.array('1 2 3 4 5'.split())
Out[598]: array(['1', '2', '3', '4', '5'], dtype='<U1')
In [599]: np.array('1 2 3 4 5'.split(),int)
Out[599]: array([1, 2, 3, 4, 5])
您打印了adc
。您是否没有注意到它不是数字数组?我强烈建议在交互式会话中逐步开发此类代码(我使用ipython
)。它有助于捕获这样的不一致之处。