Pandas 数据框中的列从浮点数到货币(负值)的输出

Kev*_*vin 5 python currency dataframe pandas

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

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

我试图将“价格”列更改为在将其导出到 Excel 电子表格时显示为货币。我使用的以下命令效果很好:

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

df.head()
Out[42]: 
    Prices
0    $-445
1  $-2,058
2    $-954
3    $-520
4    $-730
Run Code Online (Sandbox Code Playgroud)

现在我的问题是,如果我希望输出在美元符号之前有负号,我会怎么做。在上面的输出中,美元符号在负号之前。我正在寻找这样的东西:

  • -$445
  • - $2,058
  • - $954
  • - $520
  • - $730

请注意,也有正数。

And*_*ndy 5

您可以使用该locale模块和_override_localeconv字典。它没有很好的记录,但这是我在另一个答案中发现的一个技巧,以前对我有帮助。

import pandas as pd
import locale

locale.setlocale( locale.LC_ALL, 'English_United States.1252')
# Made an assumption with that locale. Adjust as appropriate.
locale._override_localeconv = {'n_sign_posn':1}

# Load dataframe into df
df['Prices'] = df['Prices'].map(locale.currency)
Run Code Online (Sandbox Code Playgroud)

这将创建一个如下所示的数据框:

      Prices
0   -$445.00
1  -$2058.00
2   -$954.00
3   -$520.00
4   -$730.00
Run Code Online (Sandbox Code Playgroud)


EdC*_*ica 4

您可以使用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
Run Code Online (Sandbox Code Playgroud)