python - 为分组条形图重新排列 pandas 数据框
问题描述
我有一个大致如下所示的熊猫数据框:
df = pd.DataFrame(data, columns=["property_1", "property_2", "value"], index=my_index)
my_index property_1 property_2 value
<1, 1, 1> "A" "X" ...
<1, 1, 1> "A" "Y" ...
<1, 1, 2> "A" "X" ...
<1, 1, 4> "A" "X" ...
<1, 1, 4> "A" "Y" ...
<1, 1, 4> "B" "X" ...
<1, 1, 4> "B" "Y" ...
我想生成一个这样的分组条形图:
这很复杂,但基本上:
- 我需要减少到对和
my_index
的每个组合都有价值的唯一索引property_1
property_2
- 我需要找到AND的唯一组合,而不仅仅是每列的唯一值!
property_1
property_2
- 我试图主要按
my_index
,然后按 和 的组合对property_1
它们进行分组property_2
我猜想解决这个问题的方法是拥有一个具有以下布局的数据框:
my_index A-X A-Y B-X B-Y ...
<1, 1, 1> ... ... NaN NaN ...
<1, 1, 2> ... ... NaN NaN ...
等等。然后可以删除其中包含任何NaN
值的列。然后,您可以调用df.plot.bar(...)
生成的数据框。
但我不确定如何以这种方式将这些行重新排列到列中。有没有人有任何想法?
编辑:我应该注意,我不需要熊猫的答案,我只是问是否有答案。如果没有,我可以自己整理数据。但也许 pandas 有一个漂亮的单行代码可以让这种工作变得更容易。
解决方案
我可能错误地理解了你的问题。但是,让我建议一些可能对您有所帮助的步骤。
首先,unique_property
从列property_1
和中添加一列property_2
,并且(如果需要)删除后者。
df[`unique_property`] = df.property_1 + df.property_2
df.drop(['property_1', 'property_2'], axis=1, inplace=True)
然后我们可以绘制数据框,按my_index
和分组unique_property
。
fig, ax = plt.subplots()
ax.set_xticks(df['my_index'].unique()) # this sets x axis.
df.groupby(["my_index", "unique_property"]).mean()['value'].unstack().plot(kind='bar', ax=ax)
最后一行的解释。
df.groupby(["my_index", "unique_property"]).mean()['value']
上面的代码将给我们 Series of ,由和value
分组。如果我们直接绘制它,那么我们将得到 ( , ) 中唯一值的所有组合作为 x 轴。这就是为什么我们需要my_index
unique_property
my_index
unique_property
unstack()
它。
这就像my_index
成为行中的唯一值和unique_property
成为列中的唯一值。
默认情况下,它会NaN
为不完整的数据产生值,例如my_index = <1,1,1>
只有AX
和AY
有值,然后BX
和BY
将被NaN
值填充。例如,我们可以替换NaN
为some_value
, then unstack(fill_value=some_value)
。
推荐阅读
- ffmpeg - 找不到用于在视频中添加水印的 FFMPEG 覆盖
- svg - Chromium 浏览器中的 SVG stroke-dasharray 绘制错误
- aspnetboilerplate - AspNetBoilerplate - 自定义 TenantResolveContributor 中的 HttpContext 为空
- ios - 在 Swift 中写入 Plist
- javascript - 在 OpenLayers 中使用属性过滤特征
- javascript - 无法在 Redux 中设置初始状态
- swift - PDF417 使用 Swift 解码并生成相同的条形码
- python - 当“计数”值为总计时,熊猫数据框中一列的平均值
- powershell - 试图将邮件从收件箱移动到 PST,但它们消失了
- spring-security-oauth2 - 将 IBM AppId 与 Spring Boot 一起使用时出现 401 UNAUTHORIZED 错误