我在 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。有办法解决这个问题吗?
改变
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)