30114
30114

Reputation: 159

Pandas DataFrame loop through all columns

I have very simple line of code:

df[df.RESP == 0].CCOL

where I list DataFrame (df) CCOL values if value in RESP column is equal to zero.

However, if I add an array (e.g. CNames=[CCOL1, CCOL2, CCOL3...]) and try to loop through the array in order to get every column values IF RESP == 0 the above line of code could not be implemented.

I tried this way:

for c in CNames:
    df[df.RESP == 0].c

Any idea how I can solve this?

Thanks!

Upvotes: 1

Views: 426

Answers (1)

joris
joris

Reputation: 139162

You are using 'attribute' acccess to the columns, but you can also get the columns using the name in [ ] ('getitem'), like df['CCOL'], and in this way you can use a variable as the column name.

In this case:

for c in CNames:
    df.loc[df.RESP == 0, c]

Using loc like above is recommended. You can also do df[df.RESP == 0][c], but this chained indexing is not always guaranteed to work if you also want to assign values to that selection.

Upvotes: 1

Related Questions