-1

I have a DataFrame through which I would like to calculate percentages; however, when attempting to do so, python spits back either 0 or 1.

For example, columns OIR.a1.d.bull and OIR.a1r1.d are arrays filled with 1s and 0s.

>>> data['OIR.a1.d.bull'].sum()
653
>>> data['OIR.a1r1.d'].sum()
320
>>> den = data['OIR.a1.d.bull'].sum()
>>> num = data['OIR.a1r1.d'].sum()
>>> den
653
>>> num
320
>>> num / den
0

I expect to see - roughly - the following.

>>> num / den
0.49004594
Brian
  • 1,729
  • 2
  • 14
  • 17

1 Answers1

0

You do integer division so your result will be an integer, which means that the fractional part of the division's result is truncated. To get a float you have to convert one of your values to a float.

float(num)/den
halex
  • 16,253
  • 5
  • 58
  • 67
  • Since OP is using Python 2.7 he also has the option of doing `from __future__ import division`. – Steven Rumbalski Mar 25 '13 at 19:01
  • 2
    @StevenRumbalski You are right and I considered to add this information, but maybe OP uses `/` for strict int division in other places of his code that will break when done as float division. – halex Mar 25 '13 at 19:03