如何从pandas DataFrame中分别识别date日期列和datetime日期时间列
解决方案
你可以在完成object列转datetime类型后,通过判断列中所有值的时间部分是否均为0时0分0秒,来区分纯日期列和带时间的日期时间列,实现代码如下:
import pandas as pd def split_date_datetime_cols(df): date_cols = [] datetime_cols = [] for col in df.columns: if df[col].dtype == 'object': try: # 先尝试将列转换为datetime类型 temp_col = pd.to_datetime(df[col]) # 判断所有值的时间部分是否都是00:00:00 if (temp_col == temp_col.dt.normalize()).all(): date_cols.append(col) # 若业务需要可直接将列转为纯日期格式存储 df[col] = temp_col.dt.date else: datetime_cols.append(col) df[col] = temp_col except ValueError: pass return date_cols, datetime_cols # 测试示例数据 df = pd.DataFrame({ 'date1':['4/10/2021', '4/11/2021','4/12/2021'], 'date_time1': ['4/11/2021 13:23:45', '4/11/2021 13:23:45', '4/11/2021 13:23:45'], 'Name': ['Bob', 'Jane', 'Alice'], 'date_time2': ['4/12/2021 13:23:45', '4/13/2021 13:23:45', '4/14/2021 13:23:45'] }) date_cols, datetime_cols = split_date_datetime_cols(df) print("纯日期列:", date_cols) print("日期时间列:", datetime_cols)
运行输出结果和期望一致:
纯日期列: ['date1']
日期时间列: ['date_time1', 'date_time2']
内容的提问来源于stack exchange,提问作者LearnerJS
相关产品推荐
相关产品推荐

