【问题标题】:Segmenting a series of Timedeltas to a minute by minute graph (pandas)将一系列时间增量分割成一分钟一分钟的图表(熊猫)
【发布时间】:2015-05-19 00:10:09
【问题描述】:

我有一个索引为 Timedelta 的数据框,范围从 0 到 5 分钟,以及一列浮点数。

这是一个示例子集:

32  0.740283
34  0.572126
36  0.524788
38  0.509685
40  0.490219
42  0.545977
44  0.444170
46  1.098387
48  2.209113
51  1.426835
53  1.536439
55  1.196625
56  1.923569

左边是以秒为单位的时间增量,右边是浮点数。

问题是在使用 pandas 绘图时,我得到一个带有以下标签的 x 轴:
0 天 00:00:00、0 天 00:01:10、0 天 00:02:15

等等。有什么方法可以重新采样(错误的词?)数据,以便我可以按分钟计算轴,同时仍将数据点保持在正确的位置?

示例代码/数据:

df = pd.DataFrame({'td':[32,34,36,38,40,42,44,51,53,152,283],
                   'val': np.random.rand(11)})

df.index = df.td.map(lambda x: pd.Timedelta(seconds=x.astype(int)))
df.drop(['td'], axis=1, inplace=True)
df.val.plot()

【问题讨论】:

    标签: python pandas matplotlib dataframe


    【解决方案1】:

    Pandas 仅为方便起见仅提供绘图功能。要完全控制,需要直接使用 Matplotlib。

    作为一种解决方法,您可以只使用 datetime 而不是 timedelta 作为索引。只要您的时间跨度在几分钟之内,Pandas 就不会绘制日期或月份。

    使用您的示例,这是可行的:

    df = pd.DataFrame({'td':[32,34,36,38,40,42,44,51,53,152,283],
                       'val': np.random.rand(11)})
    df.index = [dt(2010, 1, 1) + timedelta(seconds=int(i)) for i in df.td]
    df.drop(['td'], axis=1, inplace=True)
    df.val.plot()
    

    【讨论】:

      【解决方案2】:

      这是你想要的吗?

      import pandas as pd
      import numpy as np
      td = np.array([32,34,36,38,40,42,44,51,53,152,283])*1e9  # if you don't multiply by 1e9, then pandas will assume you are referring to nanoseconds when you use the function pd.to_datetime()
      df = pd.DataFrame({'td':td,
                         'val': np.random.rand(11)})
      
      df.index = pd.to_datetime(df.td)
      df.index = df.index.time  # select the time component of the index ... ignoring the date
      df.drop('td', 1, inplace=True)
      
      print df
                    val
      00:00:32  0.825991
      00:00:34  0.578752
      00:00:36  0.348558
      00:00:38  0.221674
      00:00:40  0.706031
      00:00:42  0.912452
      00:00:44  0.448185
      00:00:51  0.368867
      00:00:53  0.188401
      00:02:32  0.855828
      00:04:43  0.494732
      
      df.plot()  # it gets the plot you want
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-16
        • 2021-07-01
        • 2021-07-22
        • 1970-01-01
        • 1970-01-01
        • 2019-01-05
        • 1970-01-01
        相关资源
        最近更新 更多