Pandas convert float to int if decimals are 0

后端 未结 1 374
耶瑟儿~
耶瑟儿~ 2021-01-27 00:23

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          


        
相关标签:
1条回答
  • 2021-01-27 00:53

    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
    
    0 讨论(0)
提交回复
热议问题