`ValueError: operands could not be broadcast together` when attempting to plot a univariate distribution from a DataFrame column using Seaborn

`ValueError: operands could not be broadcast together` when attempting to plot a univariate distribution from a DataFrame column using Seaborn

我正在尝试绘制 Pandas DataFrame 中列的单变量分布。这是代码:

ad = summary["Acquired Delay"]
sns.distplot(ad)

这抛出:

ValueError: operands could not be broadcast together with shapes (9,) (10,) (9,)

我已经检查过这个系列是否有任何问题,将其作为 ad.values 传递,但出现了同样的错误。当我使用 ad.plot 方法时问题消失了:

ad = summary["Acquired Delay"]
ad.plot.hist()

问题消失了。情节不那么透明,但还算不错。这是 seaborn 中的常见错误吗?发生这种情况是因为我的数据包含大量零吗?

这是因为 seaborn 函数 distplot 包含行

   if bins is None:
        bins = min(_freedman_diaconis_bins(a), 50)

不指定时设置bin数,如果a的长度不是正方形,_freedman_diaconis_bins函数可以return一个非整数IQR 为 0。如果 a 由足够多的零支配,则 IQR 也将为零,例如

>>> sns.distributions.iqr([0]*8 + [1]*2)
0.0

所以我认为您的直觉是大量的零可能发挥作用是正确的。无论如何,如果我们得到一个浮点数作为 bin 的数量,那将打破 np.histogram:

>>> np.histogram([0,0,1], bins=2)
(array([2, 1], dtype=int32), array([ 0. ,  0.5,  1. ]))
>>> np.histogram([0,0,1], bins=2.1)
Traceback (most recent call last):
  File "<ipython-input-4-9aae3e6c77af>", line 1, in <module>
    np.histogram([0,0,1], bins=2.1)
  File "/home/dsm/sys/pys/3.5/lib/python3.5/site-packages/numpy/lib/function_base.py", line 249, in histogram
    n += np.bincount(indices, weights=tmp_w, minlength=bins).astype(ntype)
ValueError: operands could not be broadcast together with shapes (2,) (3,) (2,) 

所以我认为这是一个错误,您可以开工单。您可以通过直接传递垃圾箱的数量来解决它:

sns.displot(ad, bins=10)

或者如果你真的想要,你可以用像

这样的东西来修补补丁
sns.distributions._freedman_diaconis_bins_orig =
    sns.distributions._freedman_diaconis_bins
sns.distributions._freedman_diaconis_bins = lambda x:
    np.round(sns.distributions._freedman_diaconis_bins_orig(x))