pandas .to_markdown() 中的日期时间格式

Datetime formatting in pandas .to_markdown()

我有一个 pandas DataFrame,其中有一列 dtype datetime:

import pandas as pd

# Mock-up data
df = pd.DataFrame({'year': [2015, 2016],
                   'month': [2, 3],
                   'day': [4, 5]})
df = pd.to_datetime(df)

print(df)

# 0   2015-02-04
# 1   2016-03-05
# dtype: datetime64[ns]

我想使用.to_markdown()方法来显示这个DataFrame。

但是,.to_markdown() 方法以科学记数法显示日期时间:

print(df.to_markdown())

# |    |           0 |
# |---:|------------:|
# |  0 | 1.42301e+18 |
# |  1 | 1.45714e+18 |

有没有办法让 .to_markdown() 方法在 更人类可读的方式? .to_latex().to_csv().to_string() 种方法已经这样做了:

# Other .to_ methods behave as desired, eg.
print(df.to_latex())

# \begin{tabular}{ll}
# \toprule
# {} &          0 \
# \midrule
# 0 & 2015-02-04 \
# 1 & 2016-03-05 \
# \bottomrule
# \end{tabular}

pandas版本:1.3.2

制表版本:0.8.9

在底层,.to_markdown() 方法使用了 tabulate 包。 floatfmt 命名参数可用于控制浮点数的格式,但我看不出这在这里有什么用。

目前我能找到的最佳解决方案是在调用.to_markdown()方法之前将日期时间列格式化为字符串列:

print(df.astype(str).to_markdown())

# |    | 0          |
# |---:|:-----------|
# |  0 | 2015-02-04 |
# |  1 | 2016-03-05 |