bk_*_*bk_ 5 python datetime dataframe pandas
我有以下 DF:
col1 col2
1 2017-01-03 2018-03-30 08:01:32
2 2017-01-04 2018-03-30 08:02:32
Run Code Online (Sandbox Code Playgroud)
如果我这样做df.dtypes
,我会得到以下输出:
col1 datetime64[ns]
col2 datetime64[ns]
dtype: object
Run Code Online (Sandbox Code Playgroud)
然而mcol1
只包含日期信息(DATE),而col2
包含日期和时间信息(DATETIME)。
确定列是否包含 DATE 或 DATETIME 信息的最简单方法是什么?
数据生成:
import pandas as pd
# Generate the df
col1 = ["2017-01-03", "2017-01-04"]
col2 = ["2018-03-30 08:01:32", "2018-03-30 08:02:32"]
df = pd.DataFrame({"col1": col1, "col2": col2})
df["col1"] = pd.to_datetime(df["col1"])
df["col2"] = pd.to_datetime(df["col2"])
Run Code Online (Sandbox Code Playgroud)
根据this SO Question,以下函数可以完成这项工作:
def check_col(col):
try:
dt = pd.to_datetime(df[col])
if (dt.dt.floor('d') == dt).all():
return('Its a DATE field')
else:
return('Its a DATETIME field')
except:
return("could not parse to pandas datetime")
Run Code Online (Sandbox Code Playgroud)
然而,有没有更直接的方法呢?
归档时间: |
|
查看次数: |
180 次 |
最近记录: |