Pandas DataFrame中的列从浮点数输出到货币(负值) [英] Output of column in Pandas dataframe from float to currency (negative values)

查看:57
本文介绍了Pandas DataFrame中的列从浮点数输出到货币(负值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框(由负数和正数组成):

df.head()
Out[39]: 
    Prices
0   -445.0
1  -2058.0
2   -954.0
3   -520.0
4   -730.0

我正在尝试更改价格列,以便在将其导出到Excel电子表格时显示为货币。我使用的以下命令运行良好:

df['Prices'] = df['Prices'].map("${:,.0f}".format)

df.head()
Out[42]: 
    Prices
0    $-445
1  $-2,058
2    $-954
3    $-520
4    $-730
现在我的问题是,如果我希望输出在美元符号之前有负号,我该怎么办。在上面的产出中,美元符号在负面符号之前。我正在寻找这样的东西:

  • -445美元
  • --2,058美元
  • -954美元
  • -520美元
  • -730美元

请注意,也有正数。

推荐答案

您可以使用np.where并测试值是否为负数,如果是,则在美元前面加一个负号,并使用astype将序列转换为字符串:

In [153]:
df['Prices'] = np.where( df['Prices'] < 0, '-$' + df['Prices'].astype(str).str[1:], '$' + df['Prices'].astype(str))
df['Prices']

Out[153]:
0     -$445.0
1    -$2058.0
2     -$954.0
3     -$520.0
4     -$730.0
Name: Prices, dtype: object

这篇关于Pandas DataFrame中的列从浮点数输出到货币(负值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆