Search code examples
pythonpandasdataframecurrency

Output of column in Pandas dataframe from float to currency (negative values)


I have the following data frame (consisting of both negative and positive numbers):

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

I am trying to change the 'Prices' column to display as currency when I export it to an Excel spreadsheet. The following command I use works well:

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

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

Now my question here is what would I do if I wanted the output to have the negative signs BEFORE the dollar sign. In the output above, the dollar signs are before the negative signs. I am looking for something like this:

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

Please note there are also positive numbers as well.


Solution

  • You can use np.where and test whether the values are negative and if so prepend a negative sign in front of the dollar and cast the series to a string using 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