【问题标题】:ValueError: could not convert string to float: '07/06/2019'ValueError:无法将字符串转换为浮点数:'07/06/2019'
【发布时间】:2022-01-05 17:13:21
【问题描述】:

我正在对共享单车数据进行线性回归分析。我有兴趣根据其他因素预测自行车数量。

所以我像这样拆分数据:

x = df[['rain', 'temp', 'rhum', 'msl', 'wdsp', 'day', 'month', 'monthname', 'season']]

y = df['bikecount']

然后,当我到达这个阶段时:lm.fit(X_train,y_train)

它返回此错误:ValueError: could not convert string to float: '07/06/2019'

我尝试使用 df['date'] = float(df['date']) 将此列转换为浮点数,但返回错误 TypeError: cannot convert the series to 强>

我不明白为什么会不断出现这种情况。我什至对用于分析的日期列不感兴趣。任何帮助将不胜感激!

0 日期时间 6040 非空日期时间64[ns] 1 自行车计数 6040 非空 int64
2 雨 6040 非空 float64
3 临时 6040 非空 float64
4 rhum 6040 非空 int64
5 msl 6040 非空 float64
6 wdsp 6040 非空 int64
7 日期 6040 非空对象
8次6040非空对象
9 天 6040 非空对象
10 个月 6040 非空 int64
11 月名 6040 非空对象
12季6040非空对象
数据类型:datetime64ns、float64(3)、int64(4)、object(5) 内存使用量:613.6+ KB

datetime bikecount rain temp rhum msl wdsp date datetime.1 day month monthname season
2019-01-01 00:00:00 1 0.0 9.9 78 1036.0 4 01/01/2019 00:00:00 Tuesday 1 January Winter
2019-01-01 07:00:00 1 0.0 8.3 87 1036.8 2 01/01/2019 07:00:00 Tuesday 1 January Winter
2019-01-01 11:00:00 2 0.0 9.5 89 1038.8 3 01/01/2019 11:00:00 Tuesday 1 January Winter
2019-01-01 12:00:00 4 0.0 10.1 84 1038.7 3 01/01/2019 12:00:00 Tuesday 1 January Winter

【问题讨论】:

  • 对于这个日期01/01/2019,预期的结果是什么?

标签: pandas string linear-regression


【解决方案1】:

您可以将日期转换为自 1970-01-01 以来经过的秒数

# Sample
df = pd.DataFrame({'date': ['01/11/2019']}

df['date'] = pd.to_datetime(df['date'], dayfirst=True) \
               .sub(pd.to_datetime(0)) \
               .dt.total_seconds()

输出:

# Before conversion:
>>> df
         date
0  01/11/2019

# After conversion:
>>> df
           date
0  1.572566e+09

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-23
    • 2018-06-13
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    相关资源
    最近更新 更多