使用numpy从textfile读取作为一维数组的行

2024-06-16 08:36:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,包含大量的行。每行有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)

我提供textfile作为参数,目前,我得到一个错误作为

 H = len(adc)/N_SAMPS 
 TypeError: len() of unsized object

Tags: importnumpylennp整数数组headerprint
1条回答
网友
1楼 · 发布于 2024-06-16 08:36:09

我可以重现你的错误:

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)。它有助于捕捉像这样的矛盾。你知道吗

相关问题 更多 >