python-3.x - 如果小数为 0,Pandas 将 float 转换为 int

标签 python-3.x pandas dataframe

我有一个 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

我想将这些数值四舍五入到小数点后两位,我正在使用:

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

我想将这些值本身保留为适当的整数,同时在所有数字列中将其他值四舍五入到小数点后两位。我怎样才能做到这一点?

最佳答案

使用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

关于python-3.x - 如果小数为 0,Pandas 将 float 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58166923/

相关文章:

python - 来自 Groupby Python 的多列数据透视表

python - 将数据框中的多列数据(包括自动生成的列)分组

python-3.x - 将盈透证券 API 引入 Pandas

python - 数据帧参数被函数更改。如何避免其变异?

python - 如何获取列和行来自另一个数据框的列值的数据框?

python - 将抓取的列表添加到 Pandas Dataframe

python - 根据字段获取大量对象列表的最有效组合

python - 从 DataFrame 行元素生成元组

python-3.x - [错误] : Issue with threading. Thread() 在使用 Python3 执行多线程脚本时

django - Django ORM 中的 SQL 何时执行