【问题标题】:pandas.to_datetime: TypeError: invalid type promotionpandas.to_datetime:TypeError:无效的类型提升
【发布时间】:2022-02-19 17:38:33
【问题描述】:

我明白了

TypeError:无效类型提升

df.iloc[1:,0] = pd.to_datetime(np.where(m, df.iloc[1:,0], np.NaN), errors='ignore')

在下面的代码中。

这是因为在 df.iloc[1, 0] 处,空值有 m = True。我该如何解决这个问题?

m = df.iloc[1:,0].apply(lambda v: isinstance(v, datetime))
df1 ['Date'] = df.iloc[1:,0]
df1 ['m'] = m
print(df1)

df.iloc[1:,0] = pd.to_datetime(np.where(m, df.iloc[1:,0], np.NaN), errors='ignore')

**df1 的输出**


|Date            |  m   |
|                | TRUE |
|2000-01-31      | TRUE |

替代方案
我也测试了以下内容,但我仍然遇到同样的错误

df.iloc[1:,0] = pd.to_datetime(np.where(m, df.iloc[1:,0], np.NaN), errors='ignore')

不管是errors='ignore'还是errors='coerce'

m = df.iloc[1:,0].apply(lambda v: isinstance(v, datetime) if pd.isnull(v)==False else False)

df1 ['Date'] = df.iloc[1:,0]
df1 ['m'] = m
print(df1)

df.iloc[1:,0] = pd.to_datetime(np.where(m, df.iloc[1:,0], np.NaN), errors='ignore')

**df1 的输出**


|Date            |  m   |
|                | FALSE |
|2000-01-31      | TRUE |

【问题讨论】:

  • 这不是一个空单元格。我尝试了一个空单元格,但结果不同。
  • 嗨,keramat,我从 Excel 文件中读取了 df,并且在测试 pd.isnull(df1 ['Date'].iloc[0]) 时。我得到了 TRUE
  • 在转换为日期时间之前检查它。如果您提供 df 的第一行,将会很有帮助。
  • 这里实际上想要实现什么?仅将某些元素转换为日期时间?

标签: python pandas datetime


【解决方案1】:

该列作为日期时间读入。因此np.NaN 导致了错误

np.where(m, df.iloc[1:,0], np.NaN)

换成np.datetime64('NaT'),问题解决了

【讨论】:

    猜你喜欢
    • 2018-01-29
    • 1970-01-01
    • 2021-06-29
    • 2021-04-11
    • 2020-05-19
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多