首页 > 解决方案 > Python/Pandas:TypeError:float() 参数必须是字符串或数字,而不是“函数”

问题描述

我正在尝试从 .csv 文件中的两列生成图。x 轴的列采用短日期格式 mm/dd/yyyy,而 y 轴的列对应于作为常规数值的吸收测量数据。由此,我还试图从该图中收集线性回归线。这是我到目前为止所拥有的:

mydateparser = lambda x: datetime.strptime(x, '%m/%d/%y')

df = (pd.read_csv('calibrationabs200211.csv', index_col=[], parse_dates=[0],
                  infer_datetime_format=True, date_parser=mydateparser))

if mydateparser == '%m/%d/%y':
    print('Error')
else:
    mydateparser = float(mydateparser)

plt.figure(figsize=(15,7.5))

x = df.iloc[:, 0].values.reshape(-1, 1)
y = df.iloc[:, 1].values.reshape(-1, 1)
linear_regressor = LinearRegression()
linear_regressor.fit(x, y)
y_pred = linear_regressor.predict(y)

plt.scatter(x, y, color='teal')
plt.plot(x, y_pred, color='teal')

plt.show()

但是,我收到一条错误消息:

TypeError                                 Traceback (most recent call last)
<ipython-input-272-d087bdc00150> in <module>
     12     print('Error')
     13 else:
---> 14     mydateparser = float(mydateparser)
     15 
     16 plt.figure(figsize=(15,7.5))

TypeError: float() argument must be a string or a number, not 'function'

此外,如果我注释掉 If 语句,我最终会得到一个情节,但线性回归错误。我对 python、matplotlib 和 pandas 相当陌生,因此非常感谢任何帮助或反馈。谢谢!

标签: pythonpandasmatplotlib

解决方案


Python 中的函数可以用作变量,这就是您在这里所做的。如果要将函数的结果用于某事,则需要通过在函数名称后添加 () 来调用它。

mydateparser 是一个函数, mydateparser() 是调用该函数的结果。

此外,我认为您所做的比较没有意义。datetime.strptime 返回一个 datetime 对象,稍后您将其与字符串进行比较。我实际上根本不确定您要使用该块完成什么。

您的回归需要将日期转换为某种数值以进行回归。我建议使用 matplotlib 的日期转换函数,特别是 date2num,来试试这个。

应该是这样的:

from matplotlib import dates
...
x = df[0].apply(dates.date2num)

推荐阅读