You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DataFrame列按数值、分类、日期时间类型拆分?

解决DataFrame按数值、分类、日期时间列拆分的问题

筛选日期时间列的正确方式

你之前用include=['datetime']得到空结果,是因为pandas中日期时间类型的实际标识是datetime64[ns](而非单纯的datetime)。直接用以下代码即可筛选出所有日期时间列:

date_cols = df.select_dtypes(include=['datetime64'])

如果需要更精确匹配(比如带时区的日期时间),可以指定具体类型:

# 匹配带时区的日期时间列
date_cols = df.select_dtypes(include=['datetime64[ns, UTC]'])

处理字符串格式的日期列

如果你的日期列当前是字符串类型(object dtype),需要先将其转换为日期时间类型,再进行筛选:

# 将指定字符串列转为日期时间类型,errors='coerce'会把无效值转为NaT
df['your_date_column'] = pd.to_datetime(df['your_date_column'], errors='coerce')
# 再次筛选日期时间列
date_cols = df.select_dtypes(include=['datetime64'])

分类列的筛选方法

分类列可以直接通过category类型筛选:

cat_cols = df.select_dtypes(include=['category'])

如果你的分类列是字符串标签(object dtype),可以先转换为分类类型再筛选:

df['your_category_column'] = df['your_category_column'].astype('category')
cat_cols = df.select_dtypes(include=['category'])

完整拆分示例

import pandas as pd

# 拆分数值列
numeric_cols = df.select_dtypes(include=['int64', 'float64'])
# 拆分日期时间列
datetime_cols = df.select_dtypes(include=['datetime64'])
# 拆分分类列
category_cols = df.select_dtypes(include=['category'])

内容的提问来源于stack exchange,提问作者Manoranjini M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 19:05:20