首页 > 解决方案 > 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')

标签: pythonmatplotlibexception

解决方案


问题是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')

你应该只收到一条错误消息。


推荐阅读