python - 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 相当陌生,因此非常感谢任何帮助或反馈。谢谢!
解决方案
Python 中的函数可以用作变量,这就是您在这里所做的。如果要将函数的结果用于某事,则需要通过在函数名称后添加 () 来调用它。
mydateparser 是一个函数, mydateparser() 是调用该函数的结果。
此外,我认为您所做的比较没有意义。datetime.strptime 返回一个 datetime 对象,稍后您将其与字符串进行比较。我实际上根本不确定您要使用该块完成什么。
您的回归需要将日期转换为某种数值以进行回归。我建议使用 matplotlib 的日期转换函数,特别是 date2num,来试试这个。
应该是这样的:
from matplotlib import dates
...
x = df[0].apply(dates.date2num)
推荐阅读
- vaadin - 全新项目的 Vaadin 14 与 Vaadin 20
- java - 在使用 https post rest 客户端时获取 401
- android - 删除 jetpack compose 文本字段上的默认填充
- directed-acyclic-graphs - Airflow DAG:何时创建新的 dag?
- javascript - 如何在不使用 jwt 的情况下在 vue.js 中进行会话?
- scala - Spark RDD join-operation end with stackOverFlow
- javascript - 你能在 JS 正则表达式中前向引用一个命名的捕获组吗?
- flutter - MacOS 新手 - 无法从 CMD 运行颤振命令?
- discord.py - 我无法在某些不和谐频道中激活我的代码
- python - 如何在没有分隔符的熊猫的情况下拆分列