【发布时间】:2019-10-11 12:00:46
【问题描述】:
我正在处理一个学校项目,但我一直在制作分组条形图。我在网上找到了这篇文章并有解释:https://www.pythoncharts.com/2019/03/26/grouped-bar-charts-matplotlib/ 现在我有一个数据集,在 Age 列中有一个 Age 列和一个 Sex 列,代表客户的年限和性别,女性为 0,男性为 1。我想绘制男性和女性之间的年龄差异。现在我已经尝试了示例中的以下代码:
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import pylab as pyl
fig, ax = plt.subplots(figsize=(12, 8))
x = np.arange(len(data.Age.unique()))
# Define bar width. We'll use this to offset the second bar.
bar_width = 0.4
# Note we add the `width` parameter now which sets the width of each bar.
b1 = ax.bar(x, data.loc[data['Sex'] == '0', 'count'], width=bar_width)
# Same thing, but offset the x by the width of the bar.
b2 = ax.bar(x + bar_width, data.loc[data['Sex'] == '1', 'count'], width=bar_width)
这引发了以下错误:KeyError: 'count'
然后我尝试稍微更改代码并得到另一个错误:
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import pylab as pyl
fig, ax = plt.subplots(figsize=(12, 8))
x = np.arange(len(data.Age.unique()))
# Define bar width. We'll use this to offset the second bar.
bar_width = 0.4
# Note we add the `width` parameter now which sets the width of each bar.
b1 = ax.bar(x, (data.loc[data['Sex'] == '0'].count()), width=bar_width)
# Same thing, but offset the x by the width of the bar.
b2 = ax.bar(x + bar_width, (data.loc[data['Sex'] == '1'].count()), width=bar_width)
这引发了错误:ValueError: shape mismatch: objects cannot be broadcast to a single shape
现在我如何计算我做这个分组条形图的结果?
【问题讨论】:
-
年龄差是什么意思?平均年龄差?分布差异?
-
请阅读minimal reproducible example 和How to make good reproducible pandas examples。您得到的错误只是数据框中没有名为
"count"的列。但人们不知道为什么会这样。 -
现在我有一个包含 Age 列和 Sex 列的数据集:您的数据没有
'count'列,您不能这样做:data.loc[data['Sex'] == '0', 'count']跨度>
标签: python pandas numpy matplotlib