格式化 pandas y 轴以显示时间而不是总秒数

Format pandas y axis to show time instead of total seconds

我在数据框中有测量值。列是不同的对象。索引是 datetime64 索引。现在,对于每个日期,我都会对每列进行总秒数 (int) 测量。

一切都很好,我唯一的问题不是在 y 轴上显示 6000 秒,而是我想显示 1:40 来指示 1 小时 40 分钟。

我怎样才能真正做到这一点?

day         Object1  Object2
2017-01-01     6000     1234

我要

day         Object1  Object2
2017-01-01  1:40:00  00:20:34 

你能告诉我怎么做吗

可以,但是 ploting timedelta 还没有原生支持。

df['Object1'] = pd.to_timedelta(df['Object1'], unit='s')
df['Object2'] = pd.to_timedelta(df['Object2'], unit='s')

或者:

cols = ['Object1', 'Object2']
df[cols] = df[cols].apply(lambda x: pd.to_timedelta(x, unit='s'))

print (df)
          day  Object1  Object2
0  2017-01-01 01:40:00 00:20:34

但有可能 FuncFormatter:

df = pd.DataFrame({'Object1': [6000, 4000, 3000], 'Object2':[3000,5000,2110]})

import matplotlib.ticker as tkr
import datetime

def func(x, pos):
    return str(datetime.timedelta(seconds=x))
fmt = tkr.FuncFormatter(func)


ax = df.plot(x='Object1', y='Object2', rot=90)
ax.xaxis.set_major_formatter(fmt)
ax.yaxis.set_major_formatter(fmt)