【问题标题】:Change int value to .00 format将 int 值更改为 .00 格式
【发布时间】:2020-07-11 08:14:10
【问题描述】:

我有一个数据框 -

   year  month             type   amount
0  2019  9          Not Applicable    8000.00       
1  2019  10         Not Applicable    7500.00       
2  2019  11         Goods & Services  14000.35      
3  2019  11         Not Applicable    7500.00       
4  2019  12         Goods & Services  10499.00      
5  2019  12         Not Applicable    9801.00   

我有完整的列金额,但我想将另一列月份转换为这种格式 -

   year  month             type   amount
0  2019  9.00          Not Applicable    8000.00       
1  2019  10.00         Not Applicable    7500.00       
2  2019  11.00         Goods & Services  14000.35      
3  2019  11.00         Not Applicable    7500.00       
4  2019  12.00         Goods & Services  10499.00      
5  2019  12.00         Not Applicable    9801.00   

我怎样才能做到这一点。

【问题讨论】:

  • 这里的用例是什么?

标签: python django pandas django-rest-framework django-views


【解决方案1】:
df.month = df.month.astype(float)

df['month'] = df['month'].astype(float)

【讨论】:

  • 不会给你两位小数,只有一位。另外,金额有两位小数的原因是因为其中一个值是14000.35
【解决方案2】:

转换成小数点后两位的浮点数:

df['month'] = df['month'].astype('float').map('{:,.2f}'.format)
df['month']

输出:

0     9.00
1    10.00
2    11.00
3    11.00
4    12.00
5    12.00

【讨论】:

  • 这不会将其更改为具有两位小数的浮点数——这只会更改格式。根据定义,浮点数浮动意味着它适应小数位数,具体取决于列中的值。您可以将浮点数向下舍入,但不能将其舍入高于列中最大值的小数总数。例如,您将无法将金额列round 保留为小数点后 3 位,但可以将其四舍五入为 1。
  • 哦,好吧,我不知道这一点。我会留下我的答案,以防 OP 要求它采用这种格式。
  • 你的答案不一定是错的。这仅取决于OP的目标。根据阅读问题的方式,可以说您的答案应该是解决方案。
【解决方案3】:

术语是这里的关键。如果您只想更改 jupyter 笔记本中的“格式”——发送到 excel 时没有影响——那么 @SurajSubramanian 的答案应该是公认的解决方案。如果您只是想将列更改为float 格式,那么@nav610 的答案是正确的,但是您的问题的标题具体是“将 int 值更改为 .00 格式

所以,我提到,术语是关键,因为如果您真的想将基础值更改为以 .00 结尾,那么您唯一的选择是将其转换为如下所示的字符串:

df['month'] = df['month'].astype(str) + '.00'

        year    month   type                 amount
0       2019    9.00    Not Applicable       8000.00
1       2019    10.00   Not Applicable       7500.00
2       2019    11.00   Goods & Services     14000.35
3       2019    11.00   Not Applicable       7500.00
4       2019    12.00   Goods & Services     10499.00
5       2019    12.00   Not Applicable       9801.00

请参阅我的 cmets 了解更多上下文的一些答案,但答案是,这实际上取决于您的实际用例,最佳解决方案是什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多