【发布时间】:2020-02-12 18:54:01
【问题描述】:
我正在尝试从 .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 语句,我最终会得到一个情节,but with a faulty linear regression. 我对 python、matplotlib 和 pandas 还很陌生,因此非常感谢任何帮助或反馈。谢谢!
【问题讨论】:
-
你的 if/else 块没用,试着消除它,看看你是否达到了目标。
-
感谢您的回复。最后一位嵌入的图像显示了当我删除 if/else 块时会发生什么。我不能从 lambda 函数中解析出日期时间吗?我正在尝试将日期列转换为字符串或整数,以便绘图可以轻松生成 x 轴。
-
我怀疑你不能对日期进行线性回归,除非你完全确定你想要它...... if/else 块后面的代码只是按照你的意图绘制你的分析结果它。
标签: python pandas matplotlib