【问题标题】:ValueError: shape mismatch: objects cannot be broadcast to a single shape when plottingValueError:形状不匹配:绘图时无法将对象广播到单个形状
【发布时间】:2021-02-27 17:18:12
【问题描述】:

所以我有这样的数据框:

我想用条形图可视化类别与读取计数列上的数据。如果类别相同,那么它将自动对读取计数值求和,例如索引 0 和 2 中的“Megapolitan”类别。但我现在得到的是一个错误。这是我的代码:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import pylab as pl
from wordcloud import WordCloud, STOPWORDS

dataset = pd.read_csv('kompas.csv')
dataset.head()

dataset[["Total Comment", "Read Count"]] = dataset[["Total Comment", "Read Count"]].astype('int')

fig, ax = plt.subplots(figsize=(10,15))

data = dataset['Category'].value_counts()
data2 = dataset['Read Count'].value_counts() 

category = data.values 
readcount = data2.values

ax.barh(category, readcount) 
ax.set_title('Total Amount of Category on Most Popular News') 
ax.set_xlabel('Total') 
ax.set_ylabel('Category')

这是错误:

ValueError                                Traceback (most recent call last)
<ipython-input-24-b28678940ca9> in <module>()
      7 readcount = data2.values
      8 # create bar chart
----> 9 ax.barh(category, readcount)
     10 # set title and labels
     11 ax.set_title('Total Amount of Category on Most Popular News')

4 frames
<__array_function__ internals> in broadcast_arrays(*args, **kwargs)

/usr/local/lib/python3.6/dist-packages/numpy/lib/stride_tricks.py in _broadcast_shape(*args)
    189     # use the old-iterator because np.nditer does not handle size 0 arrays
    190     # consistently
--> 191     b = np.broadcast(*args[:32])
    192     # unfortunately, it cannot handle 32 or more arguments directly
    193     for pos in range(32, len(args), 31):

ValueError: shape mismatch: objects cannot be broadcast to a single shape

任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas numpy matplotlib


    【解决方案1】:

    错误是因为 datadata2 变量的形状不同。

    value_counts 函数返回唯一值的计数,这不是您想要的列读取计数

    你需要做这样的事情:

    category = pd.unique(dataset['Category'])
    category_counts = [dataset[dataset['Category']==cat].sum() for cat in category]
    ax.barh(category, category_counts)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-01
      • 1970-01-01
      • 2021-05-22
      • 2021-05-13
      • 1970-01-01
      • 2019-02-16
      • 2020-04-28
      相关资源
      最近更新 更多