python - Pandas: Adding conditionally -


i have data frame set of columns, on want perform conditional operation follows:

foo = 0 * foobar2['var1'] foo.loc[foobar2['var1'] > 0] += foobar2.loc[foobar2['var1'] > 0, 'var1'] foo.loc[foobar2['var2'] > 0] += foobar2.loc[foobar2['var2'] > 0, 'var2'] foo.loc[foobar2['var3'] > 0] -= foobar2.loc[foobar2['var3'] > 0, 'var3'] foo.loc[foobar2['var4'] > 0] -= foobar2.loc[foobar2['var4'] > 0, 'var4'] 

that is, want sum var1, var2, , subtract var3, var4 - whenever these variables positive, negative variables indicate missing values , similar in data set. code works, quite slow. there more efficient way this?

this approach fastest have tried:

foo = foobar2.clip_lower(0) foo = foo['var1']+foo['var2']-foo['var3']-foo['var4'] 

this approach tiny bit little slower:

foo = foobar2.clip_lower(0) foo['var3']*=-1 foo['var4']*=-1 foo = foo.sum(axis=1) 

you can use apply method one-liner, simpler , clearer slower approach:

foo = foobar2.clip_lower(0).apply(lambda x: x['var1']+x['var2']-x['var3']-x['var4'], axis=1) 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -