我尝试使用 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 列解压缩为四个变量这一事实之外,我没有看到任何问题。事实上,这适用于我的 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')
如果文件出现问题(如果非空行不能解释为三个 float ),则会打印有问题的行并引发异常。
关于python - 准备好列 Numpy/Matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15489708/