mat*_*ver 5 datetime python-2.7 pandas datetime64
我有一个处理 Excel 文件的脚本。发送它的部门有一个生成它的系统,我的脚本停止工作。
我突然收到Can only use .str accessor with string values, which use np.object_ dtype in pandas
以下代码行的错误:
df['DATE'] = df['Date'].str.replace(r'[^a-zA-Z0-9\._/-]', '')
Run Code Online (Sandbox Code Playgroud)
我检查了旧系统文件中日期列的类型(dtype:object)与来自新系统的文件(dtype:datetime64[ns])。
如何将日期格式更改为我的脚本可以理解的格式?
我看到了这个答案,但我对日期格式的了解并不是那么精细。
小智 8
pd.to_datetime
返回一系列datetime64
dtype,如下所述:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html
df['DATE'] = df['Date'].dt.date
Run Code Online (Sandbox Code Playgroud)
或这个:
df['Date'].map(datetime.datetime.date)
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以apply
在数据框列上使用函数将必要的列转换为字符串。例如:
df['DATE'] = df['Date'].apply(lambda x: x.strftime('%Y-%m-%d'))
Run Code Online (Sandbox Code Playgroud)
确保导入datetime
模块。
apply()
将一次获取每个单元格进行评估并应用lambda
函数中指定的格式。
您可以使用pd.to_datetime
df['DATE'] = pd.to_datetime(df['DATE'])
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
26568 次 |
最近记录: |