如果小数为0,则将浮点转换为整数

2024-09-27 07:17:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas数据框,其中一些列有数值,而其他列没有,如下所示:

City          a     b       c
Detroit       129   0.54    2,118.00
East          188   0.79    4,624.4712
Houston       154   0.65    3,492.1422
Los Angeles   266   1.00    7,426.00
Miami         26    0.11    792.18
MidWest       56    0.24    772.7813

我想将这些数值四舍五入到小数点后2位,我使用的是:

df = df.replace(np.nan, '', regex=True)

在此之后,df变为:

City          a       b       c
Detroit       129.0  0.54   2,118.0
East          188.0  0.79   4,624.47
Houston       154.0  0.65   3,492.14
Los Angeles   266.0  1.0    7,426.0
Miami         26.0   0.11   792.18
MidWest       56.0   0.24   772.78

它工作得很好,但它也将适当的整数转换为小数,即,像100这样的值被舍入为100.0。我希望数据帧如下所示:

City          a       b         c
Detroit       129    0.54      2,118
East          188    0.79      4,624.47
Houston       154    0.65      3,492.14
Los Angeles   266    1         7,426
Miami         26     0.11      792.18
MidWest       56     0.24      772.28

我希望将这些值本身保留为正确的整数,同时在所有数字列中将其他值舍入到小数点后2位。我该怎么做


Tags: 数据citypandasdf整数replace数值east
1条回答
网友
1楼 · 发布于 2024-09-27 07:17:18

使用^{}

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

相关问题 更多 >

    热门问题