简体   繁体   中英

Historgram with pandas csv read in Python

I have a data set like this:

num    gb     bw 
2.2    green  black
3.3    red    white
2.2    green  black
11.0   red    black

etc   

I am trying to come up with a subplot that contains 4 histograms, where each histogram is a type of color's data.

Here's my code:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('hw03_problem2.csv' , skiprows=1, names = ['num', 'gb', 'bw'])

#df = df.astype(float)

f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row')
df[df.gb == 'green'].num.plot.hist(ax = ax1)
df[df.gb == 'red'].num.plot.hist(ax = ax2)
df[df.bw == 'black'].num.plot.hist(ax = ax3)
df[df.bw == 'white'].num.plot.hist(ax = ax4)

plt.show()
plt.savefig('subplot_for_q2')

I am getting this error:

Empty 'DataFrame': no numeric data to plot

Probably the problem is in the "num" column format. Convert it to float before plot.

something like:

df.num = df.num.astype(float)

当您阅读excel文件时,您可以直接精确确定col num的变量类型:

df = pd.read_csv('hw03_problem2.csv' , skiprows=1, names = ['num', 'gb', 'bw'],dtype = {'num': float})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM