1

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. Now I understand where the problem was.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.