Fixing dollar signs and italic text in dataframes and Jupyter notebooks¶
When you have a monetary range ("\$4-\\$5") or a long document that uses the dollar sign, your pandas dataframes might look weird. You might have questions like:
- Why is my text italic or my numbers bigger/smaller than they should be?
- Why are my dollar signs disappearing?
- Why is everything formatted wrong?
The problem¶
We'll use a simple example, with a dataframe that includes a price range. Notice how the cost
column looks all wrong! The dollar signs are missing and the numbers look strange.
import pandas as pd
df = pd.DataFrame([
{ 'product': 'coffee', 'cost': '$2-$5'},
{ 'product': 'donut', 'cost': '$1-$7'}
])
This is because by default pandas uses something called mathjax which allows you to print very pretty mathematical formulas. If I write something that looks $like_{this}$
it will display $like_{this}$. Notice how the dollar signs mean "math goes here!"
The solution¶
To make our dataframes display correctly, we are going to disable mathjax.
import pandas as pd
pd.options.display.html.use_mathjax = False
df = pd.DataFrame([
{ 'product': 'coffee', 'cost': '$2-$5'},
{ 'product': 'donut', 'cost': '$1-$7'}
])
df
product | cost | |
---|---|---|
0 | coffee | $2-$5 |
1 | donut | $1-$7 |
There we go, our dollar signs no longer cause trouble!
And a bonus: avoiding MathJax in Markdown¶
If you try to write $4-$5
in a markdown cell, Jupyter also tries to render it as MathJax. To make that not happen, you need to add double backslashes before your dollar signs: \\$4-\\$5
.