【问题标题】:Grouping data across midnight and performing an operation using pandas在午夜对数据进行分组并使用 pandas 执行操作
【发布时间】:2021-09-22 11:00:59
【问题描述】:

我在作为自定义类的一部分的 DataFrame 中包含以下数据,我想计算夜间的统计数据。

                     LAeq,T  LAFmax,T  LA90,T
Start date & time                            
2021-08-18 22:00:00    71.5      90.4    49.5
2021-08-18 22:15:00    70.6      94.0    45.7
2021-08-18 22:30:00    69.3      82.2    48.3
2021-08-18 22:45:00    70.1      89.9    46.4
2021-08-18 23:00:00    68.9      82.4    46.0
                     ...       ...     ...
2021-08-24 08:30:00    72.3      85.0    61.3
2021-08-24 08:45:00    72.9      84.6    62.2
2021-08-24 09:00:00    73.1      86.1    62.6
2021-08-24 09:15:00    72.8      86.4    61.6
2021-08-24 09:30:00    73.2      93.5    61.5

例如,我想找到每个给定夜间时段的第 n 个最高 LAFmax,T。

夜间时段通常跨越 23:00 到 07:00,我已经成功地使用resample() 方法完成了我的目标,如下所示。

def compute_nth_lmax(self, n):
    nth_lmax = self.df["LAFmax,T"].between_time(self._night_start, self._day_start,
                                                                     include_start=True, include_end=False).resample(
        rule=self._night_length, offset=pd.Timedelta(self._night_start)).apply(
        lambda x: (np.sort(x))[-n] if x.size > 0 else np.nan).dropna()

    return nth_lmax

问题是 resample() 假设定期重新采样,当夜间时间段为 8 小时时,这可以正常工作,因此将 24 平均细分(如默认情况下 23:00 到 07:00),但是不适用于不规则的夜间时段(例如,如果我将其延长到 22:00 到 07:00)。

我曾尝试使用groupby() 完成此操作,但没有成功。

我唯一能想到的就是添加另一列来将每一行标记为“夜间 1”、“夜间 2”等,并按这些进行分组,但这感觉相当混乱。

【问题讨论】:

    标签: python pandas date grouping resampling


    【解决方案1】:

    我决定采用我认为有点不雅的方法,并在处理它们之前创建一个单独的列来标记夜间时段。尽管如此,我还是设法用两行代码实现了我的目标。

    self.df["Night-time indices"] = (self.df.index - pd.Timedelta(self._day_start)).date
    nth_event = self.df.sort_values(by=[col], ascending=False).between_time(self._night_start, self._day_start)[
                [col, period]].groupby(by=period).nth(n)
    Out[43]: 
    Night-time indices
    2021-08-18    100.0
    2021-08-19     96.9
    2021-08-20     97.7
    2021-08-21     95.5
    2021-08-22    101.7
    2021-08-23     92.7
    2021-08-24     85.8
    Name: LAFmax,T, dtype: float64
    

    【讨论】:

      猜你喜欢
      • 2017-03-17
      • 1970-01-01
      • 2016-07-28
      • 2013-07-27
      • 2016-01-13
      • 2017-09-02
      • 2017-02-24
      • 2019-06-23
      • 2017-12-18
      相关资源
      最近更新 更多