Pandas format column as currency

Question:

Given the following data frame:

import pandas as pd
df = pd.DataFrame(
        {'A':['A','B','C','D'],
         'C':[12355.00,12555.67,640.00,7000]
        })
df

    A   C
0   A   12355.00
1   B   12555.67
2   C   640.00
3   D   7000.00

I’d like to convert the values to dollars in thousands of USD like this:

    A   C
0   A   $12.3K
1   B   $12.5K
2   C    $0.6K
3   D    $7.0K

The second thing I need to do is somehow get these into a Seaborn heat map, which only accepts floats and integers. See here for more on the heat map aspect.

I’m assuming once the floats are converted to currency, they will be in object format but I’m hoping there’s a way around that.

Asked By: Dance Party2

||

Answers:

    def format(x):
        return "${:.1f}K".format(x/1000)


    df = pd.DataFrame(
        {'A':['A','B','C','D'],
         'C':[12355.00,12555.67,640.00,7000]
        })

    df['C'] = df['C'].apply(format)

    print(df)
Answered By: chenhong

Or you could use a lambda function for shorter syntax

df['C'] = df['C'].apply(lambda x: "${:.1f}k".format((x/1000)))
Answered By: Jace Whitmer

Or you could use a lambda function and f-string for even shorter shorter syntax

df['C'] = df['C'].map(lambda x: f"${x/1000:.1f}k")
Answered By: chakuRak

Flexibile formatting using Babel

If you are looking for a flexible way of formatting currency’s and numbers for different locale’s, I suggest using Babel:

Example data

df = pd.DataFrame(
        {'A':['A','B','C','D'],
         'C':[12355.00,12555.67,640.00,7000]
        })
print(df)

   A         C
0  A  12355.00
1  B  12555.67
2  C    640.00
3  D   7000.00

Formatting dollar currency:

from babel.numbers import format_currency

df["C"] = df["C"].apply(lambda x: format_currency(x, currency="USD", locale="en_US"))

   A           C
0  A  $12,355.00
1  B  $12,555.67
2  C     $640.00
3  D   $7,000.00

Formatting euro currency (notice the difference in thousands and decimal seperator):

df["C"] = df["C"].apply(lambda x: format_currency(x, currency="EUR", locale="nl_NL"))

   A            C
0  A  € 12.355,00
1  B  € 12.555,67
2  C     € 640,00
3  D   € 7.000,00
Answered By: Erfan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.