在pandas DataFrame中绘制分组数据的直方图

dre*_*eme 49 python histogram pandas

我需要一些指导来确定如何在pandas数据帧中从分组数据中绘制直方图块.这是一个例子来说明我的问题:

from pandas import DataFrame
import numpy as np
x = ['A']*300 + ['B']*400 + ['C']*300
y = np.random.randn(1000)
df = DataFrame({'Letter':x, 'N':y})
grouped = df.groupby('Letter')
Run Code Online (Sandbox Code Playgroud)

在我的无知中,我尝试了这个代码命令:

df.groupby('Letter').hist()
Run Code Online (Sandbox Code Playgroud)

失败的错误消息"TypeError:无法连接'str'和'float'对象"

任何帮助最受赞赏.

dre*_*eme 147

我正在滚动,只是在hist方法中使用by关键字找到了一种更简单的方法:

df['N'].hist(by=df['Letter'])
Run Code Online (Sandbox Code Playgroud)

这是快速扫描分组数据的一个非常方便的小捷径!

对于未来的访问者,此调用的产品如下图所示: 在此输入图像描述

  • 有没有办法在同一个情节中获得这些? (26认同)
  • 对于更大的地块;df['N'].hist(by=df['Letter']), Figsize = (16,18)) (3认同)
  • @Phani:http://stackoverflow.com/questions/6871201/plot-two-histograms-at-the-same-time-with-matplotlib (2认同)

Pau*_*aul 7

一种解决方案是直接在每个分组数据框上使用 matplotlib 直方图。您可以遍历在循环中获得的组。每个组都是一个数据框。您可以为每一个创建一个直方图。

from pandas import DataFrame
import numpy as np
x = ['A']*300 + ['B']*400 + ['C']*300
y = np.random.randn(1000)
df = DataFrame({'Letter':x, 'N':y})
grouped = df.groupby('Letter')

for group in grouped:
  figure()
  matplotlib.pyplot.hist(group[1].N)
  show()
Run Code Online (Sandbox Code Playgroud)

  • 我建议在 for 循环中拆分元组:“for index, group in grouped”,然后可以省略“[1]”。 (3认同)

cwh*_*and 7

你的函数失败了,因为你最终得到的groupby数据帧有一个分层索引和两列(Letter和N),所以当你这样做.hist()的时候,试图制作两列的直方图,因此str错误.

这是pandas绘图函数的默认行为(每列一个图),因此如果您重塑数据框以使每个字母都是一列,您将获得您想要的内容.

df.reset_index().pivot('index','Letter','N').hist()
Run Code Online (Sandbox Code Playgroud)

reset_index()仅仅是推当前索引到一个名为列index.然后pivot将您的数据帧,收集所有的值的N每一个Letter,使他们的列.结果数据框为400行(填充缺失值NaN)和三列(A, B, C). hist()然后,每列将生成一个直方图,您可以根据需要格式化绘图.


dir*_*jot 5

使用最新版本的 Pandas,你可以做到 df.N.hist(by=df.Letter)

就像上面的解决方案一样,每个子图的轴都会不同。我还没有解决那个问题。

  • 您可以使用“sharex”和“sharey”关键字来获取绘图的公共轴,即:“df.N.hist(by=df.Letter, sharey=True, sharex=True)” (3认同)