【发布时间】:2019-04-27 03:54:04
【问题描述】:
我想知道是否有人可以帮助我制作条形图来显示 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')
如果我们使用 Pandas 库中内置的方法,则无需使用 for 循环。
回答中提到的具体方法有pandas.Series.values_count()、pandas.DataFrame.sort_index()、pandas.DataFrame.plot.bar()。
【问题讨论】: