我正在尝试使用numpy.loadtext
阅读3列,但我得到错误:
ValueError: setting an array element with sequence.
数据样本:
0.5 0 -22
0.5 0 -21
0.5 0 -22
0.5 0 -21
第1列表示距离从0.5增加到6.5,每个距离有15个数据样本。
第2列是一个角度,距离每返回0.5时增加45度。
第3列包含被测量的数据(RSSI),它从大约-20减小到-70。
我使用以下代码尝试将三列加载到单独的数组中:
import numpy as np
r, theta, RSSI, null = np.loadtxt("bot1.txt", unpack=True)
我将在每个距离/角度组合下平均采样的RSSI,然后我希望将数据绘制为3D
极坐标图。但我还没走到这一步。
有什么想法,为什么np.loadtxt
不工作?
除了将3列拆分成4个变量之外,我认为没有任何问题。实际上,这可以在我的NumPy 1.6.2中使用:
r, theta, RSSI = np.loadtxt("bot1.txt", unpack=True) # 3 columns => 3 variables
在纯Python中也可以做同样的事情,以便查看是否有其他原因导致问题(如文件中的错误):
import numpy
def loadtxt_unpack(file_name):
'''
Reads a file with exactly three numerical (real-valued) columns.
Returns each column independently.
Lines with only spaces (or empty lines) are skipped.
'''
all_elmts = []
with open(file_name) as input_file:
for line in input_file:
if line.isspace(): # Empty lines are skipped (there can be some at the end, etc.)
continue
try:
values = map(float, line.split())
except:
print "Error at line:"
print line
raise
assert len(values) == 3, "Wrong number of values in line: {}".format(line)
all_elmts.append(values)
return numpy.array(all_elmts).T
r, theta, RSSI = loadtxt_unpack('bot1.txt')
如果文件出现问题(如果非空行不能解释为三个浮点数),则打印有问题的行并引发异常。