Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 425
Kevin Avatar asked Apr 13 '16 16:04

Kevin


People also ask

How do I cast a column from a float to a data frame?

Use pandas DataFrame. astype() function to convert column from string/int to float, you can apply this on a specific column or on an entire DataFrame. To cast the data type to 54-bit signed float, you can use numpy. float64 , numpy.

How do you reverse the column values in a data frame?

Reversing the rows of a data frame in pandas can be done in python by invoking the loc() function. The panda's dataframe. loc() attribute accesses a set of rows and columns in the given data frame by either a label or a boolean array.

How do I extract a value from a column in pandas?

You can extract a column of pandas DataFrame based on another value by using the DataFrame. query() method. The query() is used to query the columns of a DataFrame with a boolean expression. The blow example returns a Courses column where the Fee column value matches with 25000.


1 Answers

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
like image 151
Andy Avatar answered Nov 03 '22 02:11

Andy