我在数据框中有测量值。列是不同的对象。索引是 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
native 尚不支持。
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)
关于python - 格式化 pandas y 轴以显示时间而不是总秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49880375/