在pandas列上循环生成直方图的最佳方法是什么?

2024-06-02 04:47:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试循环数据帧中的所有列,标题为“结构数据框并为每列生成一个直方图图。在

#This is a summary of columns

Struct_DF.columns

Index(['ID', 'lh_BA1_ExV_Area', 'lh_BA2_ExV_Area', 'lh_BA3a_ExV_Area',
   'lh_BA3b_ExV_Area', 'lh_BA4a_ExV_Area', 'lh_BA4p_ExV_Area',
   'lh_BA6_ExV_Area', 'lh_BA44_ExV_Area', 'lh_BA45_ExV_Area',
   ...
   'R_presubiculum_Vol_Adj', 'R_parasubiculum_Vol_Adj',
   'R_molecular_layer_HP_Vol_Adj', 'R_GC_ML_DG_Vol_Adj', 
'R_CA3_Vol_Adj',
   'R_CA4_Vol_Adj', 'R_fimbria_Vol_Adj', 'R_HATA_Vol_Adj',
   'R_Whole_hippocampus_Vol_Adj', 'eTIV'],
  dtype='object', length=735)

# Check for normalcy of distribution of each variable.

# Set the column names

columns= Struct_DF.columns

# Loop over all columns
#using 2x2 matrix representation of histrogram specified by firs two 
#digits of subplot index and third index specifies the plot number (eg. #221)

i = 221
for col in columns:
    plt.subplot(i)
    plt.hist(Struct_DF[col])
    i+=1

我收到以下错误消息:

^{pr2}$

有没有办法并排生成这些图?在

注:此问题已根据建议答案进行了编辑。在


Tags: columnsofthe数据dfforindexcol
1条回答
网友
1楼 · 发布于 2024-06-02 04:47:22

Struct_DF.col相当于Struct_DF['col']这就是为什么你得到错误,没有列'col',你要做的是Struct_DF[col]

要绘制直方图,可以执行以下操作:

fig, axs = plt.subplots(len(df.columns), figsize=(5, 25))
for n, col in enumerate(df.columns):
    df[col].hist(ax=axs[n])

如果要使用2x2网格,可以这样做,但需要指定要打印的4列:

^{pr2}$

也可以使用ax[i].hist(df[col])代替df[col].hist(ax=ax[i]),或者:

for i in range(4):
    plt.subplot(2, 2, i)
    plt.hist(df[cols_to_plot[i]])

相关问题 更多 >