Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format numbers in a Python pandas DataFrame as currency in thousands or millions

I have a dataframe: pd.DataFrame({"Amount":[19000000, 9873200, 823449242]}), and I need to convert the numbers into currency ($) in millions. i.e. $19.00MM, $9.88MM, and $823.45MM.

Does anyone know a quick way to do this?

Thanks!

like image 916
thatMeow Avatar asked Dec 14 '22 01:12

thatMeow


1 Answers

I think the following should work:

df['($) millions'] = '$' + (df['Amount'].astype(float)/1000000).astype(str) + 'MM'

In [3]:
df['($) millions'] = '$' + (df['Amount'].astype(float)/1000000).astype(str) + 'MM'
df

Out[3]:
      Amount   ($) millions
0   19000000        $19.0MM
1    9873200      $9.8732MM
2  823449242  $823.449242MM

if needed you can also round:

In [5]:
df['($) millions'] = '$' + (df['Amount'].astype(float)/1000000).round(2).astype(str) + 'MM'
df

Out[5]:
      Amount ($) millions
0   19000000      $19.0MM
1    9873200      $9.87MM
2  823449242    $823.45MM

Another method is to apply a format on each value using apply:

In [15]:
df['($) millions'] = (df['Amount']/1000000).apply(lambda x: '${:,.2f}MM'.format(x))
df

Out[15]:
      Amount ($) millions
0   19000000     $19.00MM
1    9873200      $9.87MM
2  823449242    $823.45MM

However, I expect the first method to scale better for large datasets, although sometimes list comprehensions are faster when it comes to strings

Here is the list comprehension method:

In [17]:
df['($) millions'] = ['${:,.2f}MM'.format(x) for x in df['Amount']/1000000]
df

Out[17]:
      Amount ($) millions
0   19000000     $19.00MM
1    9873200      $9.87MM
2  823449242    $823.45MM
like image 97
EdChum Avatar answered Dec 23 '22 07:12

EdChum