【问题标题】:Plotting histograms for all columns in a pandas data frame with data in string format and nan用字符串格式和 nan 绘制 pandas 数据框中所有列的直方图
【发布时间】:2020-09-12 03:19:34
【问题描述】:

我想为我的 pandas 数据框中尽可能多的列绘制直方图。

数据框中的所有数据都以字符串格式开头。我尝试在将数据类型输入hist() 之前对其进行转换,如果无法转换给定列,则会引发异常。

我希望在输出中看到一些直方图。我只会在无法生成绘图时收到错误消息This column can not be represented as a histogram<Figure size 432x288 with 0 Axes>

感谢您的帮助!

# 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'])


# PLOTS 
for col in df:   
    try:      
        plt.figure()
        df.hist([int(col)])

    except ValueError:
        print('This column can not be represented as a histogram')
        break 

【问题讨论】:

    标签: python matplotlib exception histogram valueerror


    【解决方案1】:

    您的代码中存在一些问题:

    • int(col) 使用错误。
    • break 将在遇到任何无法转换为数字的列时立即停止您的程序。
    • plt.figure() 是多余的,因为 df.hist() 会创建自己的图形

    for col in df.columns: 
        try:      
            df[col] = pd.to_numeric(df[col]) 
            df.hist(column=col)
        except ValueError:
            print('This column can not be represented as a histogram')
    

    【讨论】:

    • 使用玩具数据集和您的代码,我的输出中没有任何直方图,只有错误消息。我不明白为什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 2014-06-03
    • 2019-11-05
    • 2019-08-29
    • 2012-11-16
    • 2019-09-12
    相关资源
    最近更新 更多