Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/pandas idiom for if/then/else [duplicate]

Tags:

python

pandas

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
like image 755
bjornarneson Avatar asked Jun 15 '13 22:06

bjornarneson


People also ask

How can pandas detect duplicates?

By using 'last', the last occurrence of each set of duplicated values is set on False and all others on True. By setting keep on False, all duplicates are True. To find duplicates on specific column(s), use subset .


1 Answers

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
like image 161
BrenBarn Avatar answered Sep 18 '22 22:09

BrenBarn