首页 > 解决方案 > TypeError:使用 seaborn.countplot() 时,参数 'obj' 的类型不正确(预期列表,得到 DataFrame)

问题描述

名为快乐的数据来自一项调查。幸福的值是浮点型。请看下面:

   happiness   drink_frequency
0  1.0           7.0
1  3.0           4.0
2  2.0           3.0
3  2.0           9.0
4  3.0           5.0
5  1.0           5.0
6  1.0           2.0
7  NaN           NaN
8  2.0           7.0
9  1.0           8.0
10 3.0           6.0

我想使用 countplot() 来绘制幸福的数量。但事实证明'TypeError:参数'obj'的类型不正确(预期列表,得到DataFrame)'。

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/opt/conda/lib/python3.6/site-packages/seaborn/utils.py in categorical_order(values, order)
    507             try:
--> 508                 order = values.cat.categories
    509             except (TypeError, AttributeError):

/opt/conda/lib/python3.6/site-packages/pandas/core/generic.py in __getattr__(self, name)
   3080                 return self[name]
-> 3081             return object.__getattribute__(self, name)
   3082 

AttributeError: 'DataFrame' object has no attribute 'cat'

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
/opt/conda/lib/python3.6/site-packages/seaborn/utils.py in categorical_order(values, order)
    510                 try:
--> 511                     order = values.unique()
    512                 except AttributeError:

/opt/conda/lib/python3.6/site-packages/pandas/core/generic.py in __getattr__(self, name)
   3080                 return self[name]
-> 3081             return object.__getattribute__(self, name)
   3082 

AttributeError: 'DataFrame' object has no attribute 'unique'

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-33-57f69e3b6bb8> in <module>()
      1 
----> 2 ax=sns.countplot(data=happy,x=['happiness'])

/opt/conda/lib/python3.6/site-packages/seaborn/categorical.py in countplot(x, y, hue, data, order, hue_order, orient, color, palette, saturation, dodge, ax, **kwargs)
   3357                           estimator, ci, n_boot, units,
   3358                           orient, color, palette, saturation,
-> 3359                           errcolor, errwidth, capsize, dodge)
   3360 
   3361     plotter.value_label = "count"

/opt/conda/lib/python3.6/site-packages/seaborn/categorical.py in __init__(self, x, y, hue, data, order, hue_order, estimator, ci, n_boot, units, orient, color, palette, saturation, errcolor, errwidth, capsize, dodge)
   1594         """Initialize the plotter."""
   1595         self.establish_variables(x, y, hue, data, orient,
-> 1596                                  order, hue_order, units)
   1597         self.establish_colors(color, palette, saturation)
   1598         self.estimate_statistic(estimator, ci, n_boot)

/opt/conda/lib/python3.6/site-packages/seaborn/categorical.py in establish_variables(self, x, y, hue, data, orient, order, hue_order, units)
    197 
    198                 # Get the order on the categorical axis
--> 199                 group_names = categorical_order(groups, order)
    200 
    201                 # Group the numeric data

/opt/conda/lib/python3.6/site-packages/seaborn/utils.py in categorical_order(values, order)
    511                     order = values.unique()
    512                 except AttributeError:
--> 513                     order = pd.unique(values)
    514                 try:
    515                     np.asarray(values).astype(np.float)

/opt/conda/lib/python3.6/site-packages/pandas/core/algorithms.py in unique(values)
    341     """
    342 
--> 343     values = _ensure_arraylike(values)
    344 
    345     # categorical is a fast-path

/opt/conda/lib/python3.6/site-packages/pandas/core/algorithms.py in _ensure_arraylike(values)
    164         inferred = lib.infer_dtype(values)
    165         if inferred in ['mixed', 'string', 'unicode']:
--> 166             values = lib.list_to_object_array(values)
    167         else:
    168             values = np.asarray(values)

TypeError: Argument 'obj' has incorrect type (expected list, got DataFrame)

我不知道如何纠正错误。有人有解决方案吗?任何帮助表示赞赏。

谢谢!

标签: pythonseaborn

解决方案


错误来自它应该是ax=sns.countplot(data=happy, x='happiness')而不是ax=sns.countplot(data=happy, x=['happiness'])

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

sns.set(style="darkgrid")
happy = {'drink_frequency': pd.Series([1.0,3.0,2.0,2.0,3.0,1.0,1.0,float('nan'),2.0,1.0,3.0], index=['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']),
             'happiness': pd.Series([7.0,4.0,3.0,9.0,5.0,5.0,2.0,float('nan'),7.0,8.0,6.0], index=['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'])}
happy = pd.DataFrame(happy)
print (happy)
ax=sns.countplot(data=happy, x='happiness')
sns.set(style="darkgrid")
plt.show()

图片


推荐阅读