我正在尝试阅读3列,numpy.loadtext但我收到错误:
ValueError: setting an array element with sequence.
Run Code Online (Sandbox Code Playgroud)
数据样本:
0.5 0 -22
0.5 0 -21
0.5 0 -22
0.5 0 -21
Run Code Online (Sandbox Code Playgroud)
第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)
Run Code Online (Sandbox Code Playgroud)
我将在每个距离/角度组合中对采样的RSSI进行平均,然后我希望将数据绘制为3D极坐标图.虽然我还没有这么远.
有什么想法,为什么np.loadtxt不工作?
除了将3列拆分为4个变量之外,我没有看到任何问题.事实上,这适用于我的NumPy 1.6.2,其中:
r, theta, RSSI = np.loadtxt("bot1.txt", unpack=True) # 3 columns => 3 variables
Run Code Online (Sandbox Code Playgroud)
也可以在纯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')
Run Code Online (Sandbox Code Playgroud)
如果文件有问题(如果非空行不能解释为三个浮点数),则会打印有问题的行并引发异常.