median() 尝试将列更改为数字

问题描述 投票:0回答:1

我在 if-else 列表理解中使用中值(),如下所示:

summary_frame = pd.DataFrame({
# ...
"50%": [df[col].median() if "float" or "int" or "time" or in str(df[col].dtype) else df[col].mode() for col in df.columns]
# ...
})

如果数据类型不是数字,则应默认为 mode(),该模式在数据类型不是数字时起作用。

但是,它尝试将序列转换为数字并抛出 TypeError。有办法解决这个问题吗?

python pandas typeerror
1个回答
0
投票

改变

if "float" or "int" or "time" or in str(df[col].dtype)

if any(t in str(df[col].dtype for t in ("float", "int", "time"))
Python 中的

or
与英语不同,它不会自动分配比较操作。你不会写

if x or y or z in something

这被解析为

if x or y or (z in something)
© www.soinside.com 2019 - 2024. All rights reserved.