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 point2f
: 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.
- Project target does not exist. angular
- Property ‘apiurl’ does not exist on type ‘{}’.
- Prisma insert multiple rows
- Protobuf compiler version 23.1 doesn’t match library version 4.23.1
- Python selenium send keys without element
- Pulling 1 repository checkout conflict with files:
- Psycopg2.errors.numericvalueoutofrange: integer out of range
- Pandas float division by zero