【问题标题】:AttributeError: 'DataFrame' object has no attribute 'cat' and a series of exceptionsAttributeError: 'DataFrame' 对象没有属性 'cat' 和一系列异常
【发布时间】:2020-09-25 13:11:08
【问题描述】:

我正在尝试通过形成 Pandas 数据框从 csv 文件的数据中绘制箱线图。这是CSV的行数和列数:

data_final = pd.read_csv('/home/hp/Myo_dataset/final_mean.csv', header=None )
total_rows=len(data_final.axes[0])
total_cols=len(data_final.axes[1])
print("Number of Rows: "+str(total_rows))
print("Number of Columns: "+str(total_cols))

输出

Number of Rows: 400
Number of Columns: 9

这是箱线图的代码:

plt.figure(figsize=(10,10))
sns.boxplot(x=data_final.iloc[:,8], y=data_final.iloc[:,0],data=data_final, showfliers=False, saturation=1)
plt.xlabel('Classes of Gestures')
plt.ylabel('Feature extracted from Sensor 1')
plt.show()

我收到以下错误日志:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/seaborn/utils.py in categorical_order(values, order)
    525             try:
--> 526                 order = values.cat.categories
    527             except (TypeError, AttributeError):

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/pandas/core/generic.py in __getattr__(self, name)
   3613                 return self[name]
-> 3614             return object.__getattribute__(self, name)
   3615 

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

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/seaborn/utils.py in categorical_order(values, order)
    528                 try:
--> 529                     order = values.unique()
    530                 except AttributeError:

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/pandas/core/generic.py in __getattr__(self, name)
   3613                 return self[name]
-> 3614             return object.__getattribute__(self, name)
   3615 

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

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-33-9b1bba723aae> in <module>()
      1 
      2 plt.figure(figsize=(10,10))
----> 3 sns.boxplot(x=data_final.iloc[:,8], y=data_final.iloc[:,0],data=data_final, showfliers=False, saturation=1)
      4 plt.xlabel('Classes of Gestures')
      5 plt.ylabel('Feature extracted from Sensor 1')

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/seaborn/categorical.py in boxplot(x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, dodge, fliersize, linewidth, whis, notch, ax, **kwargs)
   2229     plotter = _BoxPlotter(x, y, hue, data, order, hue_order,
   2230                           orient, color, palette, saturation,
-> 2231                           width, dodge, fliersize, linewidth)
   2232 
   2233     if ax is None:

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/seaborn/categorical.py in __init__(self, x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, dodge, fliersize, linewidth)
    444                  width, dodge, fliersize, linewidth):
    445 
--> 446         self.establish_variables(x, y, hue, data, orient, order, hue_order)
    447         self.establish_colors(color, palette, saturation)
    448 

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/seaborn/categorical.py in establish_variables(self, x, y, hue, data, orient, order, hue_order, units)
    201 
    202                 # Get the order on the categorical axis
--> 203                 group_names = categorical_order(groups, order)
    204 
    205                 # Group the numeric data

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/seaborn/utils.py in categorical_order(values, order)
    529                     order = values.unique()
    530                 except AttributeError:
--> 531                     order = pd.unique(values)
    532                 try:
    533                     np.asarray(values).astype(np.float)

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/pandas/core/algorithms.py in unique(values)
    362 
    363     table = htable(len(values))
--> 364     uniques = table.unique(values)
    365     uniques = _reconstruct_data(uniques, dtype, original)
    366 

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Float64HashTable.unique()

ValueError: Buffer has wrong number of dimensions (expected 1, got 2)

<matplotlib.figure.Figure at 0x7ff27f995a58>

如果我更改箱线图 X 轴的数据,它会顺利运行(但是,这不是我的意图):

sns.boxplot(x=data_final.iloc[:,7], y=data_final.iloc[:,0],data=data_final, showfliers=False, saturation=1)

这是数据框 data_final 和第 8 列的子集:

  print(data_final.head())
  print('--------------------------------------------')
  print(data_final.iloc[:,8].head())

输出:

               0        1        2        3        4        5        6        7  8
    258   5650.0   7627.0   7906.0  11137.0   4229.0   4455.0  19328.0  25212.0  6
    391  25734.0  36965.0  40745.0  27203.0  22482.0   9187.0  29116.0  28223.0  8
    394  15436.0  18634.0  34686.0  24717.0  20505.0   8869.0  25787.0  23753.0  8
    132  41836.0   8416.0   7861.0   6466.0   6324.0  17479.0  21717.0  35430.0  3
    144  53333.0  10018.0   8223.0   7736.0   7686.0  21683.0  23300.0  48648.0  3
    --------------------------------------------
    258    6
    391    8
    394    8
    132    3
    144    3

   Name: 8, dtype: int64

【问题讨论】:

  • 你能展示你的数据框的一个子集(最终数据)吗?第8栏的内容是什么?检查 dtype
  • 我添加了该信息。请检查。
  • @DavideBrex 如果你不能解决问题,那么你能建议我做一些修改以使代码运行吗?
  • 我尝试使用数据框的一小部分运行您的代码,它对我来说效果很好。也许如果您的数据不合理,您可以在此处附加指向您的文件的链接final_mean.csv,我可以再试一次。

标签: python pandas dataframe seaborn boxplot


【解决方案1】:

这样试试:

df = pd.read_csv("final_mean.csv", header=None)
plt.figure(figsize=(10,10))
sns.boxplot(x=8, y=0,data=df,  showfliers=False, saturation=1)
plt.xlabel('Classes of Gestures')
plt.ylabel('Feature extracted from Sensor 1')
plt.show()

或者:

sns.boxplot(x=df.iloc[:,8], y=df.iloc[:,0], showfliers=False, saturation=1)

输出:

【讨论】:

  • 使用新代码,它显示数据框中的行数是 399 而不是 400。
  • 你说得对,我现在解决了这个问题。检查更新的答案!
  • 我这边仍然报错。我通过修改这一行来修复它: sns.boxplot(x=data_final.iloc[:,8], y=data_final.iloc[:,0], showflyers=False, saturation=1) 参见前面的代码。我感谢您为帮助我所做的所有辛勤工作。我不明白为什么会发生在我身上。如果它在您这边工作得很好,我会选择它作为接受的答案。
  • 我排除了这个参数:data=data_final
猜你喜欢
  • 1970-01-01
  • 2013-10-23
  • 2017-01-24
  • 2018-10-10
  • 2019-08-18
  • 2021-01-20
  • 2020-05-16
  • 2018-10-04
  • 2021-04-05
相关资源
最近更新 更多