astanin / python-tabulate

Pretty-print tabular data in Python, a library and a command-line utility. Repository migrated from bitbucket.org/astanin/python-tabulate.
https://pypi.org/project/tabulate/
MIT License
2.08k stars 162 forks source link

The `missingval` argument doesn't recognise `np.nan` values, it only recognises `None` #316

Open paulrougieux opened 5 months ago

paulrougieux commented 5 months ago

Related to

Current behaviour

The missingval argument doesn't recognise np.nan values, it only recognises None


import pandas
import numpy as np
from tabulate import tabulate
df = pandas.DataFrame({"x": [1, 2], "y": [0, np.nan]})
print(tabulate(df,floatfmt=".0f", missingval="-",tablefmt="grid"))
--
+---+---+-----+
| 0 | 1 |   0 |
+---+---+-----+
| 1 | 2 | nan |
+---+---+-----+

In [6]: print(tabulate(df.replace(np.nan, None),floatfmt=".0f", missingval="-",tablefmt="grid"))
+---+---+---+
| 0 | 1 | 0 |
+---+---+---+
| 1 | 2 | - |
+---+---+---+

Note: In practice I use the data frame .to_markdown() methods which calls tabulate in the background, as explained in the pandas documentation of DataFrame.to_markdown

In [7]: print(df.to_markdown(floatfmt=".0f", index=False, missingval="-"))
|   x |   y |
|----:|----:|
|   1 |   0 |
|   2 | nan |

In [8]: print(df.replace(np.nan, None).to_markdown(floatfmt=".0f", index=False, missingval="-"))
|   x |   y |
|----:|----:|
|   1 |   0 |
|   2 |   - |

Proposed behaviour

The missingval argument should recognise np.nan as a missing value. This would help avoid having to replace them with df.replace(np.nan, None).