python - Python直方图输出同时尝试和输出中的代码除外
问题描述
我正在循环遍历 pandas 数据框(仅具有字符串格式数据)以为每列创建一个直方图。
我正在处理异常,因为我不希望所有列都包含可以在直方图中表示的数据。
问题是,当我运行以下代码时,对于我的数据集中的 5 列,我总共得到 4 个直方图和 5 个自定义错误消息。
这是怎么回事?此外,直方图没有任何标题,它们应该有。
谢谢!
# PACKAGES
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# DATA
data = {'col1': ['id345', 'id873', 'id972', 'id472', 'id930'],
'col2': ['1.0', '0.0', '1.0', '0.0', np.nan],
'col3': ['0.281', '0.380', '0.240', '0.260', '0.222'],
'col4': ['0.17', '0.184', '0', '0.22', np.nan],
'col5': ['1', '1', '0', np.nan, '0']
}
df = pd.DataFrame(data, columns = ['col1', 'col2', 'col3', 'col4', 'col5'])
# HISTOGRAMS
for i, col in enumerate(df.columns):
try:
pd.to_numeric(df[col]).hist(fig=plt.figure(i))
plt.title(col)
except:
print('My error message')
解决方案
问题是plt.figure(i)
哪个是图形实例,pd.Series.hist()
不知道如何处理。你可以做:
for i, col in enumerate(df.columns):
try:
# try to convert to numeric first
# if this fails, error is thrown and jump to `Except`
s = pd.to_numeric(df[col])
# create an axis instance and pass to `hist`
fig, ax = plt.subplots()
s.hist(ax=ax)
plt.title(col)
except:
print('My error message')
你应该只收到一条错误消息。
推荐阅读
- java - 为什么没有'else',它会在BTree的preoder遍历中抛出java.lang.NullPointerException?
- python - 在 Python 中使用文件 POST 请求
- python - 芹菜:如何以可靠和可测试的方式获取队列大小
- cordova - 构建失败时的 Ionic 5
- c++ - 如果条件带有时间参数
- core-data - Index Beyond Bounds / EXC_BAD_ACCESS 核心数据删除 SwiftUI
- vue.js - 使用 v-for 将动态创建的元素上的 @click 事件限制为调用它的元素
- javascript - 错误:元素类型无效,需要字符串(对于内置组件)或类/函数(对于复合元素)
- javascript - Puppeteer 浏览器和页面即时关闭,page.evaluate 不适用于 bloc 2
- database - 限制 MariaDB 中小数点后的位置数