2

I'm trying to write some code which looks at the column names and sets the column value to 0 if that column name contains a specific string. I have a dataset with columns similar to this:

date apples_sold bananas_sold pineapples_sold orange_sold

I want to update any columns with the string "apple" to make every row 0 for that column. If the column doesn't contain "apple" then the value should remain.

I tried looping through the column names but am unsure the syntax as I don't want to hardcode the specific column names.

1 Answer 1

3

Try loc update with .str.contains:

df.loc[:, df.columns.str.contains('apple')] = 0
Sign up to request clarification or add additional context in comments.

1 Comment

That's amazing. I wish I asked this before spending hours on this. So eloquent, yet simple. Thank you!

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.