Peter
Peter

Reputation: 782

Dividing 2 integer columns in pandas DataFrame in Python 3 returns rounded integer instead of float

I have the following pandas DataFrame:

df = pd.DataFrame({"id": [1, 2, 3],
                   "A": [54, 53, 50],
                   "B": [52, 49, 46]})

Now I want a new column C that is the result of dividing the values in column B by the values of column A. However, when I run:

df["C"] =  df["B"] / df["A"]

the result is:

    id  A   B   C
0   1   54  52  1
1   2   53  49  1
2   3   50  46  1

The column C seems to be automatically rounded up to an integer, which should not happen. I read some other Stack Overflow posts, which say that in Python 3 (which I'm using) the conversion to float should automatically happen. From another post I tried this:

df["C"] =  df["B"] * 1.00 / df["A"]

But that still gave the same wrong result. How to solve this?

Upvotes: 1

Views: 1861

Answers (2)

Nk03
Nk03

Reputation: 14949

Try. -

df["C"] = df.A.astype(float) / df.B.astype(float)

Upvotes: 2

Peter
Peter

Reputation: 782

The issue was I set

pd.options.display.float_format = '{:,.0f}'.format

But commented it out and thought this would solve it. Instead, changing it to:

pd.options.display.float_format = None

solved the problem

Upvotes: 0

Related Questions