在for循环内绘制groupby时遇到麻烦。我正在尝试为数据中的每个分类特征生成一个groupby条形图,但是当我运行循环时,什么也没发生。
代码如下:
for col in df.select_dtypes(include = ['object']):
plt.figure(figsize = (12, 7))
df.groupby(col).col2.mean().plot(kind = 'bar')
plt.show();
有人知道为什么它不生成任何图吗?
答案 0 :(得分:0)
您可以创建需要分组的所需列的列表,然后遍历这些列,例如:
让我们假设您总是希望对数据帧中的每个其他列按均值对col3进行分组,因此您首先返回除col3以外的所有其他数据帧的列表,然后循环遍历该列表:
neededCols = [c for c in df if c is not 'col3']
for col in neededCols:
plt.figure(figsize = (12, 7))
df.groupby(col).col3.mean().plot(kind = 'bar')
plt.show()