Pandas中astype()转换类型后df.dtypes未生效问题咨询
问题原因及解决办法
核心原因:
astype()方法执行后会返回一个转换后的新Series对象,不会直接修改原DataFrame中的列数据。你当前的代码仅生成了转换结果但未将其赋值回原列,所以原DataFrame的OrderDate列类型保持不变。解决方法:
- 将转换结果赋值回原列,覆盖原有数据:
df_raw['OrderDate'] = df_raw.OrderDate.astype('datetime64[ns]') - 更推荐使用
pd.to_datetime()方法,它能自动识别多种日期字符串格式,容错性更强:import pandas as pd df_raw['OrderDate'] = pd.to_datetime(df_raw['OrderDate'])
- 将转换结果赋值回原列,覆盖原有数据:
执行上述任一操作后,再调用df_raw.dtypes就能看到OrderDate列的类型变为datetime64[ns]了。
内容的提问来源于stack exchange,提问作者Fwooper Fwooper
相关产品推荐
相关产品推荐

