Kevin
Kevin

Reputation: 1729

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:

Please note there are also positive numbers as well.

Upvotes: 7

Views: 8268

Answers (2)

Andy
Andy

Reputation: 50570

You can use the locale module and the _override_localeconv dict. It's not well documented, but it's a trick I found in another answer that has helped me before.

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)

This creates a dataframe that looks like this:

      Prices
0   -$445.00
1  -$2058.00
2   -$954.00
3   -$520.00
4   -$730.00

Upvotes: 5

EdChum
EdChum

Reputation: 394101

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

Upvotes: 4

Related Questions