【问题标题】:Format all timedelta objects in Pandas Dataframe格式化 Pandas Dataframe 中的所有 timedelta 对象
【发布时间】:2021-11-23 09:32:16
【问题描述】:

问题

我不喜欢 Pandas 显示 timedelta 的方式,因为

  • 小数点后面的位数太多
  • “天”可以拼写为“d”

如何根据我的自定义格式在 DataFrame 中显示所有 timedeltas?例如

timedelta(days=34, hours=7, seconds=33.7) -> "34d 07:00:34"

timedelta(hours=7, seconds=4) -> "07:00:04" (right aligned)

以下是没有帮助的:

  • 添加 datetime.min + mytimedelta.strftime("%jd %H:%M%D") (source) 这在当时有效,但在几天内它是一次性的。
  • 我在 pandas 显示选项中找不到有用的选项。
  • with pd.option_context("display.precision", 0): 应该解决小数问题的时间增量被忽略。

这是格式化单个时间增量的方法

(source)

td = timedelta(days=34, hours=7, seconds=33.7)
days = td.days
hours, minutes = divmod(td.seconds, 3600)
minutes, seconds = divmod(minutes, 60)
seconds += td.microseconds > 5e5
f"{days}d {hours:02}:{minutes:02}:{seconds:02}"

MCVE 玩游戏:

from datetime import timedelta
df = pd.DataFrame([
    ["short", timedelta(seconds=15.4), timedelta(hours=7, seconds=4)],
    ["long", timedelta(days=34, hours=7, seconds=4), timedelta(days=2)]
])
print(df)

       0                      1               2
0  short 0 days 00:00:15.400000 0 days 07:00:04
1   long       34 days 07:00:04 2 days 00:00:00

myprettyprint(df)  # doesn't exist yet

       0             1            2
0  short      00:00:15  0d 07:00:04
1   long  34d 07:00:04  2d 00:00:00

【问题讨论】:

    标签: python datetime string-formatting timedelta


    【解决方案1】:

    这就是pandas.DataFrame.to_string 的用途:

    def timedelta_to_string(self):
        """Custom string formatting for timedelta."""
        days = self.days
        hours, minutes = divmod(self.seconds, 3600)
        minutes, seconds = divmod(minutes, 60)
        seconds += self.microseconds > 5e5
        return f"{days}d {hours:02}:{minutes:02}:{seconds:02}"
    
    print(df.to_string(
        formatters=dict.fromkeys([1, 2], timedelta_to_string)
    ))
    
           0            1           2
    0  short  0d 00:00:15 0d 07:00:04
    1   long 34d 07:00:04 2d 00:00:00
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-12
      • 2021-03-31
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 2016-03-19
      • 1970-01-01
      相关资源
      最近更新 更多