JavaEar 专注于收集分享传播有价值的技术资料

TypeError: expected 1D vector for x

I am getting the error:

TypeError: expected 1D vector for x

with regards to this line:

coefficients = np.polyfit(x1, y1, 1)

coefficients = np.polyfit(x1, y1, 1)
polynomial = np.poly1d(coefficients)
ys = polynomial(x1)

x1 & y1 are;

x = frame_query("select * from table",db)
y = frame_query("select * from table",db)

x1 = np.array(x)
y1 = np.array(y)

Consisting of 736 rows of data. I want to regress one row onto the other. Could someone help please?



  1. You'll want to turn the data frame into a 1D array. First let me create a data frame

    import pandas
    d = pandas.DataFrame([[1,2],[3,4],[5,6]],columns=['x1','y1'])

    I think the following does what you want:

    import numpy
    x1 = numpy.array(d['x1'])
    y1 = numpy.array(d['y1'])

    I think the problem you are having is that the arrays you're creating have an additional dimension. For example, the arrays a and b below "look" just like x1 and y1,

    a = numpy.array([[1,3,5]])
    b = numpy.array([[2,4,6]])

    but because of the double bracket ([[...]]) they are actually two-dimensional. I can reduce the dimension by selecting just the 0th column:

    x1 = a[0,:]
    y1 = b[0,:]

    Then the polyfit will work. EDIT: if you look at the shape of the arrays (e.g. x1.shape) you should be able to tell if you have "extra dimensions."

  2. 参考答案2
  3. Try to make x1 and y1 np.array:

    x1 = np.array([45,34,12])
    y1 = np.array([19,46,22])