Jaweria Amjad
Jaweria Amjad

Reputation: 63

iterating over the columns of a dataframe in pandas

I am trying to plot some histograms of the values in the columns of a dataframe in pandas and I want to loop over the columns for a compact code but the code keeps throwing an error?

for c in df.columns:
    axes[i,0].hist(df[df.num>0].c.tolist())
    i +=1
AttributeError: 'DataFrame' object has no attribute 'c'

Upvotes: 0

Views: 61

Answers (2)

Dotun
Dotun

Reputation: 91

You can't use dot notation with variables. I think what you want to go for is

for c in df.columns:
    axes[i,0].hist(df[df.num>0][c].tolist())
    i +=1

Upvotes: 0

BENY
BENY

Reputation: 323376

Chain column can not use in the for loop

axes[i,0].hist(df.loc[df.num>0,c].tolist())

Upvotes: 1

Related Questions