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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With