krizajb
krizajb

Reputation: 1814

compare column value pandas

I have two columns which I create like this:

df_o['a'] = (df['sell'] == 1).resample(interval).sum().astype(int)
df_o['b'] = (df['sell'] == 0).resample(interval).sum().astype(int)

I wish to calculate ratio between those two columns, ie:

df_o['ratioab'] = df_o['a'] / df_o['b']

This works, but I can't find a way to avoid x/0 or 0/x which for pandas equals Inf. I this case I wish to set df_o['ratioab'] = 0

This doesn't work:

if (0 == df_o['a']).all() | (0 == df_o['b']).all():
    df_ohlc['ratioab'] = 0

Upvotes: 1

Views: 54

Answers (2)

Dawid_Sielski
Dawid_Sielski

Reputation: 384

You can also use something like this:

df_o[df_o['ratioab'] == np.inf] = 0

Upvotes: 0

jezrael
jezrael

Reputation: 862406

One possible solution is:

df_o['ratioab'] = (df_o['a'] / df_o['b']).replace(np.inf, 0)

Upvotes: 1

Related Questions