首页 > 解决方案 > 为分组条形图重新排列 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"           ...

我想生成一个这样的分组条形图:

所需的组条形图

这很复杂,但基本上:

  1. 我需要减少到对和my_index的每个组合都有价值的唯一索引property_1property_2
  2. 我需要找到AND的唯一组合,而不仅仅是每列的唯一值!property_1 property_2
  3. 我试图主要按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 有一个漂亮的单行代码可以让这种工作变得更容易。

标签: pythonpandasdataframe

解决方案


我可能错误地理解了你的问题。但是,让我建议一些可能对您有所帮助的步骤。

首先,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_indexunique_propertymy_indexunique_property

unstack()它。

这就像my_index成为行中的唯一值和unique_property成为列中的唯一值。

默认情况下,它会NaN为不完整的数据产生值,例如my_index = <1,1,1>只有AXAY有值,然后BXBY将被NaN值填充。例如,我们可以替换NaNsome_value, then unstack(fill_value=some_value)


推荐阅读