python - 制作一个条形图来表示 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()
。
解决方案
我相信你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()
详情:
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
推荐阅读
- python - TypeError:__str__ 返回非字符串(类型错误)
- php - SQLSTATE [23000]:违反完整性约束:1048 列“profile_percentage”在原则上不能为空
- php - move_uploaded_file 给出“无法打开流:权限被拒绝”
- r - 如何从 MVC 控制器操作方法触发 R 脚本并将结果接收到数据表中?
- c - 字数统计程序打印不同的字数
- r - downloadHandler (Shiny) 误解用户路径名中的斜杠
- javascript - 如何在 for 循环中选择数组的每个第二个元素?
- php - 如何在 Laravel 5.6 中获取哪个用户发送了请求?
- ruby-on-rails - 在 localhost 中使用自定义子域 url 时无法验证 CSRF 令牌的真实性
- c# - Xamarin Forms - 如何从您输入的数据中填充 ListView?