我正在绘制数据帧的子集,而一个子集恰好只有一行。这是我能想到它导致问题的唯一原因。这就是它的样子:
problem_dataframe = prob_df[prob_df['Date']==7]
problem_dataframe.head()
我尝试做:
sns.distplot(problem_dataframe['floatTime'])
但我收到错误:
TypeError:未确定对象的len()
有人请告诉我导致这种情况的原因以及如何解决这个问题?
答案 0 :(得分:1)
通过设置TypeError
解决bins=1
。
但是,它揭示了一个不同的错误ValueError: x must be 1D or 2D
,它由Matplotlib的hist()
中的内部函数触发,称为_normalize_input()
:
import pandas as pd
import seaborn as sns
df = pd.DataFrame(['Tue','Feb',7,'15:37:58',2017,15.6196]).T
df.columns = ['Day','Month','Date','Time','Year','floatTime']
sns.distplot(df.floatTime, bins=1)
输出:
ValueError Traceback (most recent call last)
<ipython-input-25-858df405d200> in <module>()
6 df.columns = ['Day','Month','Date','Time','Year','floatTime']
7 df.floatTime.values.astype(float)
----> 8 sns.distplot(df.floatTime, bins=1)
/home/andrew/anaconda3/lib/python3.6/site-packages/seaborn/distributions.py in distplot(a, bins, hist, kde, rug, fit, hist_kws, kde_kws, rug_kws, fit_kws, color, vertical, norm_hist, axlabel, label, ax)
213 hist_color = hist_kws.pop("color", color)
214 ax.hist(a, bins, orientation=orientation,
--> 215 color=hist_color, **hist_kws)
216 if hist_color != color:
217 hist_kws["color"] = hist_color
/home/andrew/anaconda3/lib/python3.6/site-packages/matplotlib/__init__.py in inner(ax, *args, **kwargs)
1890 warnings.warn(msg % (label_namer, func.__name__),
1891 RuntimeWarning, stacklevel=2)
-> 1892 return func(ax, *args, **kwargs)
1893 pre_doc = inner.__doc__
1894 if pre_doc is None:
/home/andrew/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_axes.py in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)
6141 x = np.array([[]])
6142 else:
-> 6143 x = _normalize_input(x, 'x')
6144 nx = len(x) # number of datasets
6145
/home/andrew/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_axes.py in _normalize_input(inp, ename)
6080 else:
6081 raise ValueError(
-> 6082 "{ename} must be 1D or 2D".format(ename=ename))
6083 if inp.shape[1] < inp.shape[0]:
6084 warnings.warn(
ValueError: x must be 1D or 2D
_normalize_input()
已从Matplotlib(looks like sometime last year)中移除,因此我猜Seaborn指的是引擎盖下的旧版本。
您可以在this old commit中看到_normalize_input()
:
def _normalize_input(inp, ename='input'):
"""Normalize 1 or 2d input into list of np.ndarray or
a single 2D np.ndarray.
Parameters
----------
inp : iterable
ename : str, optional
Name to use in ValueError if `inp` can not be normalized
"""
if (isinstance(x, np.ndarray) or
not iterable(cbook.safe_first_element(inp))):
# TODO: support masked arrays;
inp = np.asarray(inp)
if inp.ndim == 2:
# 2-D input with columns as datasets; switch to rows
inp = inp.T
elif inp.ndim == 1:
# new view, single row
inp = inp.reshape(1, inp.shape[0])
else:
raise ValueError(
"{ename} must be 1D or 2D".format(ename=ename))
...
但我无法弄明白为什么inp.ndim!=1
。在输入上执行相同的np.asarray().ndim
会按预期返回1
:
np.asarray(df.floatTime).ndim # 1
如果您想使用sns.distplot()
进行单值输入,那么您将面临一些障碍。
建议的解决方法
检查单个元素df.floatTime
,如果是这种情况,只需使用plt.hist()
代替{无论如何distplot
与KDE一起使用):
plt.hist(df.floatTime)