Reputation: 25
So I'm trying to fit a curve from some data from a .csv file that has two variable (columns) called 'angle' and 'velocity' (see code). I tried using numpy.polyfit
on the data arrays:
But the code gives me this error
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'float'
Both the data sets ('angle' and 'velocity') are arrays.
Here's the code:
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()
Upvotes: 2
Views: 2997
Reputation: 880547
Notice that when the NumPy array has a string dtype, addition with a float raises a TypeError:
In [12]: np.asarray([3], dtype='|S1') + 0.0
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'float'
When you read the data from the CSV file, you must convert the strings to numerical values, otherwise you will be loading strings into the NumPy array.
You could fix the problem by using float
here:
for i in range(len(data)):
angle.append(float(data[i][0]))
velocity.append(float(data[i][1]))
A more efficient solution would be to use np.loadtxt or np.genfromtxt to load the csv data directly into a NumPy array instead of using csv.reader
. The details of how to do that depends on the format of the csv file.
Upvotes: 2