Skip to content Skip to sidebar Skip to footer

Pandas Convert Float To Int If Decimals Are 0

I have a pandas dataframe, in which some columns have numeric values while others don't, as shown below: City a b c Detroit 129 0.54 2,118.00 East

Solution 1:

Use g format:

General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.

The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4 <= exp < p, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the '#' option is used.

Positive and negative infinity, positive and negative zero, and nans, are formatted as inf, -inf, 0, -0 and nan respectively, regardless of the precision.

A precision of 0 is treated as equivalent to a precision of 1. The default precision is 6.

df.update(df.select_dtypes(include=np.number).applymap('{:,g}'.format))
print (df)
          City    a     b         c
0      Detroit  129  0.54     2,118
1         East  188  0.79  4,624.47
2      Houston  154  0.65  3,492.14
3  Los Angeles  266     1     7,426
4        Miami   26  0.11    792.18
5      MidWest   56  0.24   772.781

Post a Comment for "Pandas Convert Float To Int If Decimals Are 0"