【问题标题】:datetime conversion - TypeError: only integer scalar arrays can be converted to a scalar index日期时间转换 - 类型错误:只有整数标量数组可以转换为标量索引
【发布时间】:2021-07-21 21:41:50
【问题描述】:

我有这样一个数据框:

ds  y
22/02/18 13 1
28/07/19 14 1
09/02/21 15 2

我想将 ds 列设为日期时间并使用:

df1['ds'] = pd.to_datetime(df1['ds'], format = '%d/%m/%y %H')

但是得到:

TypeError: only integer scalar arrays can be converted to a scalar index

我必须在这里做什么?问题是,之前完全相同的操作有效,但现在不可能了。

编辑:感谢所有答案!我在我的脚本中发现了一个可能导致错误的错误。请投票结束这个问题。

【问题讨论】:

  • 你能放一个更好的数据框版本吗?目前还不清楚每列的元素在哪里开始和结束。哪个是你的“ds”栏的内容,哪个是“y”栏的内容?

标签: python pandas datetime typeerror


【解决方案1】:

当数据时间为“字符串”格式时,转换工作正常。那么也许先将其转换为字符串格式?

data = {'ds':['22/02/18 13', '28/07/19 14', '09/02/21 15']}
df1 = pd.DataFrame(data=data)
df1['ds'] = pd.to_datetime(df1['ds'], format = '%d/%m/%y %H')
df1

输出:

ds
0   2018-02-22 13:00:00
1   2019-07-28 14:00:00
2   2021-02-09 15:00:00

希望这会有所帮助吗?

【讨论】:

    猜你喜欢
    • 2018-05-29
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2021-03-26
    • 1970-01-01
    • 2021-09-25
    相关资源
    最近更新 更多