因此,我尝试根据 .csv 文件中的一些数据拟合一条曲线,该文件具有两个名为“角度”和“速度”的变量(列)(请参阅代码)。我尝试在数据数组上使用 numpy.polyfit:
但是代码给了我这个错误
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'float'
数据集(“角度”和“速度”)都是数组。
代码如下:
import csv as csv
import pylab as plt
import numpy as np
readdata = csv.reader(open("stuff.csv"))
data = []
for row in readdata:
data.append(row) #add(append) row stuff in a variable called 'data'
header = data[0]
data.pop(0)
angle = []
velocity = []
for i in range(len(data)):
angle.append(data[i][0])
velocity.append(data[i][1])
#print (angle, velocity)
"""
result = lowess(angle, velocity)
print (result)
plt.plot(angle,result, '+')
plt.show()
"""
z = np.polyfit(angle, velocity, 3) # The problem is right here
f = np.poly1d(z)
angle_new = np.linspace(angle[0], angle[-1], 50)
velocity_new = f(angle_new)
plt.plot(angle, velocity, angle_new, velocity_new)
plt.xlim(angle[0]-1, angle[-1]+1)
plt.show()
最佳答案
请注意,当 NumPy 数组具有字符串数据类型时,与 float 相加会引发类型错误:
In [12]: np.asarray([3], dtype='|S1') + 0.0
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'float'
从 CSV 文件读取数据时,必须将字符串转换为数值,否则会将字符串加载到 NumPy 数组中。
您可以在此处使用 float
解决该问题:
for i in range(len(data)):
angle.append(float(data[i][0]))
velocity.append(float(data[i][1]))
更有效的解决方案是使用 np.loadtxt或np.genfromtxt将 csv 数据直接加载到 NumPy 数组中,而不是使用 csv.reader。具体操作方法取决于 csv 文件的格式。
关于arrays - numpy.polyfit 显示 TypeError : unsupported operand type(s) for +: 'numpy.ndarray' and 'float' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30223017/