Pandas format column as currency

Formatting a Pandas Column as Currency

In order to format a Pandas column as currency, you can use the map function along with the appropriate format specifier. Here’s a detailed explanation with examples:

First, let’s consider a sample DataFrame:

import pandas as pd

# Create a sample DataFrame
data = {'Product': ['Apple', 'Banana', 'Orange'],
        'Price': [0.99, 1.25, 0.75]}
df = pd.DataFrame(data)

print(df)

The result will be:

  Product  Price
0   Apple   0.99
1  Banana   1.25
2  Orange   0.75

This DataFrame contains two columns: ‘Product’ and ‘Price’. Now, let’s format the ‘Price’ column as a currency:

# Format the 'Price' column as currency
df['Price'] = df['Price'].map('${:,.2f}'.format)

print(df)

The result will be:

  Product  Price
0   Apple  $0.99
1  Banana  $1.25
2  Orange  $0.75

As you can see, the ‘Price’ column is now formatted as currency using the {:,.2f} format specifier. This format specifier means:

  • {} : Placeholder for the value
  • : : Separator between the value and the format specification
  • , : Thousands separator
  • . : Decimal point
  • 2f : Two decimal places

You can modify the format specifier according to your requirements. For example:

# Format the 'Price' column as currency with a different format specifier
df['Price'] = df['Price'].map('€{:,.3f}'.format)

print(df)

The result will be:

  Product  Price
0   Apple  €0.990
1  Banana  €1.250
2  Orange  €0.750

In this example, the ‘Price’ column is formatted as currency using the €{:,.3f} format specifier, which means:

  • : Euro symbol
  • {:,.3f} : Three decimal places

That’s how you can format a Pandas column as currency. Remember, the map function applies the specified format to each value in the column.

Leave a comment