【问题标题】:How to properly format time so that it can be displayed correctly when plotting using matplotlib如何正确格式化时间,以便在使用 matplotlib 绘图时正确显示时间
【发布时间】:2020-11-22 17:20:25
【问题描述】:

我有两列时间和值的数据框。 Time 列中的实际值以 seconds.milliseconds 格式给出。 我以以下方式创建了数据框:

test_df = pd.DataFrame({'Time': [1595006371.756430732,1595006372.502789381 ,1595006373.784446912 ,1595006375.476658051], 'Values': [4,5,6,10]},index=list('0123'))

然后我检查了时间列的类型

test_df.dtypes

时间列类型为 float64。 然后,我使用

将 float64 转换为 datetime64[ns]
test_df['Time']=pd.to_datetime(test_df['Time'], unit='ms')

我为时间设置标签并使用绘制值

import matplotlib.pyplot as plt
plt.xlabel('Time')
ax=test_df.set_index('Time).plot(lw=3)

时间以适当的格式显示小时:分钟:秒。 问题是时间列中的值显示不正确。在上面的例子中,时间跨度在一秒以内,而实际的时间跨度是几秒。

当我对整个数据集使用相同的过程时,我得到的时间跨度以秒为单位,但它应该以小时为单位。换句话说,看剧情,我会说经过的时间是几十秒,而不是应该的几个小时。

我该如何解决这个问题?

【问题讨论】:

    标签: python datetime matplotlib plot datetime-format


    【解决方案1】:

    您可以使用转换器方法转换和存储 seconds.millieconds。然后你可以添加到列表中并在你的图表中使用它。

    from pandas import DataFrame
    
    
    def convert(second, milli_second):
        millis = int(milli_second)
        seconds = (millis/1000) % 60
        seconds = int(seconds) + int(second)
        minutes = (millis/(1000*60)) % 60
        minutes = int(minutes)
        hours = (millis/(1000*60*60)) % 24
    
        return "%d:%d:%d" % (hours, minutes, seconds)
    
    
    if __name__ == '__main__':
        results = []
        test_df = DataFrame({'Time': [1595006371.756430732,
                                      1595006372.502789381,
                                      1595006373.784446912,
                                      1595006375.476658051],
                             'Values': [4, 5, 6, 10]}, index=list('0123'))
    
        for i in test_df['Time']:
            sec, ms = str(i).split('.')
            result = convert(sec, ms)
            results.append(result)
    
        print(results)
    

    输出:

    ['2:6:1595006375', '1:23:1595006419', '0:13:1595006377', '0:7:1595006431']
    

    【讨论】:

    • 感谢您的回复。如果时间列中的值以秒为单位,有没有办法使用日期时间进行这种转换?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多