【发布时间】: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 的第一行,将会很有帮助。
-
这里实际上想要实现什么?仅将某些元素转换为日期时间?