2 回答
TA贡献2011条经验 获得超2个赞
请使用df.filter(like='date', axis=1)(包含“日期”)或df.filter(regex='^date', axis=1)(starts with date) and apply pd.to_datetime to thedf进行过滤
原始 df dtypes
df.filter(like='date', axis=1).dtypes#filter columns that contain date and check their dtypes
df.dtypes
date_today object
date_adm object
dtype: object
解决方案
df.filter(like='date', axis=1).apply(lambda x: pd.to_datetime(x))
新数据类型
df.filter(like='date', axis=1).apply(lambda x: pd.to_datetime(x)).dtypes
df.dtypes
date_today datetime64[ns]
date_adm datetime64[ns]
dtype: object
TA贡献1851条经验 获得超5个赞
让我们使用stack和filter
df = pd.DataFrame({'date1' : ['20200105','20210305'],
'date2' : [20200103, 20210309],
'id' : [0,1] })
date1 date2 id
0 20200105 20200103 0
1 20210305 20210309 1
df.loc[:,df.filter(like='date').columns] = df.filter(like='date')\
.stack()\
.apply(pd.to_datetime,
format='%Y%m%d')\
.unstack()
print(df)
date1 date2 id
0 2020-01-05 2020-01-03 0
1 2021-03-05 2021-03-09 1
print(df.dtypes)
date1 datetime64[ns]
date2 datetime64[ns]
id int64
dtype: object
添加回答
举报