使用median()触发TypeError,如何避免非数值列强制转换?
问题解决方法
你的代码有两个核心问题导致报错,逐个解决即可:
1. 条件判断逻辑完全错误
原代码里的"float" or "int" or "time" in str(df[col].dtype)写法等价于("float") or ("int") or ("time" in ...),因为非空字符串的布尔值为True,所以这个条件永远为真,所有列都会执行median(),非数值列自然触发类型错误。
正确的做法是直接用pandas提供的类型判断工具,比字符串匹配更准确可靠:
pd.api.types.is_numeric_dtype():判断是否为数值类型(int/float等)pd.api.types.is_datetime64_dtype():判断是否为时间类型
2. mode()返回的是Series而非单一值
直接把mode()的结果放入列表,会导致DataFrame的单元格是Series对象,需要提取单个值(比如取第一个众数),同时要处理众数为空的边界情况(比如列全为空时)。
修正后的代码
列表推导式版本
import pandas as pd summary_frame = pd.DataFrame({ # ... 保留你的其他列定义 "50%": [ df[col].median() if pd.api.types.is_numeric_dtype(df[col]) or pd.api.types.is_datetime64_dtype(df[col]) else df[col].mode().iloc[0] if not df[col].mode().empty else None for col in df.columns ] })
可读性更好的自定义函数版本
如果列数多、逻辑复杂,用自定义函数更清晰:
import pandas as pd def get_stat(series): if pd.api.types.is_numeric_dtype(series) or pd.api.types.is_datetime64_dtype(series): return series.median() mode_res = series.mode() return mode_res.iloc[0] if not mode_res.empty else None summary_frame = pd.DataFrame({ # ... 其他列 "50%": [get_stat(df[col]) for col in df.columns] })
这样就能实现:数值/时间列取中位数,其他列取第一个众数,空列返回None避免报错。
内容的提问来源于stack exchange,提问作者plotmaster473
相关产品推荐
相关产品推荐

