首页 > 解决方案 > 制作一个条形图来表示 Pandas 系列中的出现次数

问题描述

我想知道是否有人可以帮助我制作条形图来显示熊猫系列中值的频率。

我从形状为 (2000, 7) 的 Pandas DataFrame 开始,然后从那里提取最后一列。该列是形状(2000,)。

我提到的系列中的条目从 0 到 17 不等,每个都有不同的频率,我尝试使用条形图绘制它们,但遇到了一些困难。这是我的代码:

# First, I counted the number of occurrences.

count = np.zeros(max(data_val))

for i in range(count.shape[0]):
    for j in range(data_val.shape[0]):
        if (i == data_val[j]):
            count[i] = count[i] + 1

'''
This gives us
count = array([192., 105., ... 19.])
'''

temp = np.arange(0, 18, 1) # Array for the x-axis.

plt.bar(temp, count)

我在最后一行代码上遇到错误,说the objects cannot be broadcast to a single shape.

我最终想要的是一个条形图,其中每个条对应一个从 0 到 17 的整数值,每个条的高度(即 y 轴)代表频率。

谢谢你。


更新

我决定使用人们在下面给出的建议发布固定代码,以防万一遇到类似问题的人将来能够看到我修改后的代码。

data = pd.read_csv("./data/train.csv") # Original data is a (2000, 7) DataFrame
# data contains 6 feature columns and 1 target column.

# Separate the design matrix from the target labels.
X = data.iloc[:, :-1]
y = data['target']


'''
The next line of code uses pandas.Series.value_counts() on y in order to count
the number of occurrences for each label, and then proceeds to sort these according to
index (i.e. label).

You can also use pandas.DataFrame.sort_values() instead if you're interested in sorting
according to the number of frequencies rather than labels.
'''
y.value_counts().sort_index().plot.bar(x='Target Value', y='Number of Occurrences')

在此处输入图像描述

for如果我们使用 Pandas 库中内置的方法,则无需使用循环。

答案中提到的具体方法是pandas.Series.values_count()pandas.DataFrame.sort_index()pandas.DataFrame.plot.bar()

标签: pythonpandasbar-chart

解决方案


我相信你value_counts需要Series.plot.bar

df = pd.DataFrame({
         'a':[4,5,4,5,5,4],
         'b':[7,8,9,4,2,3],
         'c':[1,3,5,7,1,0],
         'd':[1,1,6,1,6,5],
})

print (df)
   a  b  c  d
0  4  7  1  1
1  5  8  3  1
2  4  9  5  6
3  5  4  7  1
4  5  2  1  6
5  4  3  0  5


df['d'].value_counts(sort=False).plot.bar()

图片

如果可能,缺少某些值并需要将其设置为0添加reindex

df['d'].value_counts(sort=False).reindex(np.arange(18), fill_value=0).plot.bar()

G

详情

print (df['d'].value_counts(sort=False))
1    3
5    1
6    2
Name: d, dtype: int64

print (df['d'].value_counts(sort=False).reindex(np.arange(18), fill_value=0))
0     0
1     3
2     0
3     0
4     0
5     1
6     2
7     0
8     0
9     0
10    0
11    0
12    0
13    0
14    0
15    0
16    0
17    0
Name: d, dtype: int64

推荐阅读