18

After performing calculations on an entire pandas dataframe, I need to go back and override variable calculations (often setting to zero) based on the value of another variable(s). Is there a more succinct/idiomatic way to perform this kind of operation?

df['var1000'][df['type']==7] = 0
df['var1001'][df['type']==7] = 0
df['var1002'][df['type']==7] = 0
...
df['var1099'][df['type']==7] = 0

Is there a pandas-y way to do something like this?

if (df['type']==7):
    df['var1000'] = 0
    df['var1001'] = 0
    df['var1002'] = 0
    ...
    df['var1099'] = 0
3
  • @cs95 how is this a duplicate of the question posted more than 4 years after?
    – ayorgo
    Apr 25, 2019 at 16:03
  • @ayorgo duplicates do not only have to be fixed based on chronological ordering. IMO both of the answers in the other question do a good (better) job of answering the question than the answer below (that uses a deprecated function to add to things).
    – cs95
    Apr 25, 2019 at 16:54
  • @cs95 I bet it'd spark quite a debate if mentioned on meta. Oh, wait... meta.stackexchange.com/a/147651 Seems legit then, although making the banner misleading. Btw, the reason I noticed is because of the reference from pandas.pydata.org/pandas-docs/stable/user_guide/…
    – ayorgo
    Apr 25, 2019 at 17:56

1 Answer 1

27
df.ix[df.type==7, ['var1001', 'var1002']] = 0

If you're doing it on all columns, you can just do df.ix[df.type==7] = 0. Or of course if you have a list of the columns whose values you want to replace, you can pass that list in the second slot:

columnsToReplace = ['var1001', 'var1002', ...]
df.ix[df.type==8, columnsToReplace] = 0
3
  • 6
    And can use: var10_cols = [col for col in df.columns if isinstance(col, basestring) and col.startswith('var10')] Jun 15, 2013 at 22:13
  • 2
    Nice! Came here from the cookbook! Dec 22, 2016 at 10:41
  • 2
    ix is deprecated, use .loc instead.
    – cs95
    Apr 25, 2019 at 16:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.