Pandas 根据另一列的值从 DataFrame 的列堆叠直方图?
Pandas stacked histogram from column of DataFrame by values of another column?
假设我有这样的数据:
A 列
B 列
富
5
酒吧
46
巴兹
100
富
10
...
...
我正在尝试从 pandas DataFrame 创建堆叠直方图,该数据帧堆叠通过按 A 列对 B 列的值进行分组而获得的系列。
我使用了 pd.hist(by='Column A', column='Column B', stacked=True)
,但是,正如文档所说,'by' 将根据指定列中的每个唯一值创建直方图。
有什么提示吗?
IIUC,你想要这个:
df.pivot(columns="Column A")["Column B"].plot(kind="hist", stacked=True)
你可以这样做:
# taking count since histogram anyway represents the frequencies in each bin.
grp = df.groupby("col_A").agg("count")
plt.hist([grp.index, grp.values.reshape(3,)], bins=3, range=(1,6), stacked=True, color = ['r','g'])
plt.show()
假设我有这样的数据:
A 列 | B 列 |
---|---|
富 | 5 |
酒吧 | 46 |
巴兹 | 100 |
富 | 10 |
... | ... |
我正在尝试从 pandas DataFrame 创建堆叠直方图,该数据帧堆叠通过按 A 列对 B 列的值进行分组而获得的系列。
我使用了 pd.hist(by='Column A', column='Column B', stacked=True)
,但是,正如文档所说,'by' 将根据指定列中的每个唯一值创建直方图。
有什么提示吗?
IIUC,你想要这个:
df.pivot(columns="Column A")["Column B"].plot(kind="hist", stacked=True)
你可以这样做:
# taking count since histogram anyway represents the frequencies in each bin.
grp = df.groupby("col_A").agg("count")
plt.hist([grp.index, grp.values.reshape(3,)], bins=3, range=(1,6), stacked=True, color = ['r','g'])
plt.show()