绘制pandas数据框中所有列的直方图,数据格式为字符串和纳米。

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

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

数据框架中的所有数据都是在一个 绳子 格式开始。我试过在输入数据类型之前先将其转换为 hist()如果给定的列不能被转换,则会引发一个异常。

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

谢谢你的帮助!我想为我的pandas数据框架中尽可能多的列绘制直方图。

# 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个回答
0
投票

你的代码中问题不多。

  • 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')
© www.soinside.com 2019 - 2024. All rights reserved.