遍历数据框中的列以按类别生成直方图
Loop over columns in a dataframe to produce histograms by category
我想根据结果变量(目标列)调查我的 df 中所有特征(列)的频率分布。搜索了解决方案后,我从 here 中找到了这个漂亮的片段,它遍历特征并为来自 Scikit-learn 的癌症数据集中的特征生成直方图。
import numpy as np
import matplotlib.pyplot as plt
# from matplotlib.pyplot import matplotlib
fig,axes =plt.subplots(10,3, figsize=(12, 9)) # 3 columns each containing 10 figures, total 30 features
malignant=cancer.data[cancer.target==0] # define malignant
benign=cancer.data[cancer.target==1] # define benign
ax=axes.ravel()# flat axes with numpy ravel
for i in range(30):
_,bins=np.histogram(cancer.data[:,i],bins=40)
ax[i].hist(malignant[:,i],bins=bins,color='r',alpha=.5)
ax[i].hist(benign[:,i],bins=bins,color='g',alpha=0.3)
ax[i].set_title(cancer.feature_names[i],fontsize=9)
ax[i].axes.get_xaxis().set_visible(False) # the x-axis co-ordinates are not so useful, as we just want to look how well separated the histograms are
ax[i].set_yticks(())
ax[0].legend(['malignant','benign'],loc='best',fontsize=8)
plt.tight_layout()# let's make good plots
plt.show()
假设我的 df 具有跨连续列组织的所有特征和目标变量,我将如何遍历我的列以重现直方图。我考虑过的一种解决方案是 groupby
方法。
df.groupby("class").col01.plot(kind='kde', ax=axs[1])
非常感谢任何想法!
实际上你可以使用 sns.FacetGrid
来做到这一点:
# Random data:
np.random.seed(1)
df = pd.DataFrame(np.random.uniform(0,1,(100,6)), columns=list('ABCDEF'))
df['class'] = np.random.choice([0,1], p=[0.3,0.7], size=len(df))
# plot
g = sns.FacetGrid(df.melt(id_vars='class'),
col='variable',
hue='class',
col_wrap=3) # change this to your liking
g = g.map(sns.kdeplot, "value", alpha=0.5)
输出:
我想根据结果变量(目标列)调查我的 df 中所有特征(列)的频率分布。搜索了解决方案后,我从 here 中找到了这个漂亮的片段,它遍历特征并为来自 Scikit-learn 的癌症数据集中的特征生成直方图。
import numpy as np
import matplotlib.pyplot as plt
# from matplotlib.pyplot import matplotlib
fig,axes =plt.subplots(10,3, figsize=(12, 9)) # 3 columns each containing 10 figures, total 30 features
malignant=cancer.data[cancer.target==0] # define malignant
benign=cancer.data[cancer.target==1] # define benign
ax=axes.ravel()# flat axes with numpy ravel
for i in range(30):
_,bins=np.histogram(cancer.data[:,i],bins=40)
ax[i].hist(malignant[:,i],bins=bins,color='r',alpha=.5)
ax[i].hist(benign[:,i],bins=bins,color='g',alpha=0.3)
ax[i].set_title(cancer.feature_names[i],fontsize=9)
ax[i].axes.get_xaxis().set_visible(False) # the x-axis co-ordinates are not so useful, as we just want to look how well separated the histograms are
ax[i].set_yticks(())
ax[0].legend(['malignant','benign'],loc='best',fontsize=8)
plt.tight_layout()# let's make good plots
plt.show()
假设我的 df 具有跨连续列组织的所有特征和目标变量,我将如何遍历我的列以重现直方图。我考虑过的一种解决方案是 groupby
方法。
df.groupby("class").col01.plot(kind='kde', ax=axs[1])
非常感谢任何想法!
实际上你可以使用 sns.FacetGrid
来做到这一点:
# Random data:
np.random.seed(1)
df = pd.DataFrame(np.random.uniform(0,1,(100,6)), columns=list('ABCDEF'))
df['class'] = np.random.choice([0,1], p=[0.3,0.7], size=len(df))
# plot
g = sns.FacetGrid(df.melt(id_vars='class'),
col='variable',
hue='class',
col_wrap=3) # change this to your liking
g = g.map(sns.kdeplot, "value", alpha=0.5)
输出: