0

I have a column that has Amount rounded to 2 decimal places. So there are two types of enteries, one of the form 359.00 and others 359.78. I want to remove .00 from the first form of enteries to make it interger(359) keeping the decimal format of other number intact.

1 Answers1

0

Data are floating numbers

A column don't have mixed types. Assuming your data are stored as floating numbers (dtype: float64), they will remain floats. What you can do is to use a custom format so that they are shown on the screen as you wish, but internally they remains floats. For example:

dfa = pd.DataFrame.from_records([(1,), (3.34,), (2.49,), (5,), (7,)], columns=['Amount'])
pd.options.display.float_format = lambda x : "{:2.2f}".format(x).rstrip('0').rstrip('.')
print(dfa)

This prints:

   Amount  
0       1  
1    3.34  
2    2.49  
3       5  
4       7

Data are strings

If instead your data are just strings representing numbers (dtype: object) you can use pandas.applymap to actually edit the strings according to a format style.

dfb = pd.DataFrame.from_records([("1.00",), ("3.34",), ("2.49",), ("5.00",), ("7.00",)], columns=['Amount'])
dfbb = dfb.applymap(lambda x : str(x).rstrip('0').rstrip('.'))
print(dfbb)

This prints (again):

  Amount
0      1
1   3.34
2   2.49
3      5
4      7

Data are floating numbers but you want strings

In this case you can combine the two methods:

dfc = dfa.applymap(lambda x : "{:2.2f}".format(x).rstrip('0').rstrip('.'))
print(dfc)

Starting from a dataframe with floating numbers, you end with a dataframe of formatted strings. It prints the same, no need to touch pandas format settings.

Credits to this answer for the basic idea.

Valentino
  • 7,291
  • 6
  • 18
  • 34