在具有多个系统读数的 pandas DataFrame 中,如何计算每个系统的每日平均值和 select 最近的平均值

In a pandas DataFrame with readings for multiple systems, how can I calculate daily averages and select the most recent average for each system

我已将数据集导入 pandas DataFrame。每行是来自特定系统 (id) 在特定时间戳 (time_stamp) 的一个读数(振幅)。每个系统都有多个读数。

我想select每个系统的最近日平均值。

这是我的数据集的一个例子:

df.head(6)

                 time_stamp     amplitude
id      
id1     2018-06-19 00:36:00     16163.1
id1     2018-06-19 01:19:00     16399.7
id1     2018-06-19 01:24:00     16463.3
id1     2018-06-19 03:51:00     16139.4
id2     2018-03-17 03:41:00     11886.0
id2     2018-03-17 03:41:00     12293.6

带有时间戳的列已转换为 pd.TimeStamp:

df.dtypes

time_stamp        datetime64[ns]
amplitude         float64
dtype: object

我从计算每个系统的日平均值开始。

为此,我将时间戳替换为日期,按系统 ID(索引)对行进行分组并计算每个日期的平均值。这将创建一个具有 MultiIndex ['id'、'date']

的 DataFrame
av = df.copy()

# work with dates rather than time stamps
av['date'] = av.time_stamp.dt.date
av.drop('time_stamp', axis=1, inplace=True)

# calculate daily means for each system
av = av.groupby([av.index,'date']).mean()
av
                    amplitude
id      date    
id1     2018-03-17  13923.500
        2018-04-17  14130.325
        2018-12-22  13532.650
id2     2018-03-17  12234.720
        2018-04-17  12367.050
id3     2018-06-19  16291.375

此时我卡住了。

有人可以建议我如何使用每个系统的最新平均值创建一个新的 DataFrame 吗?像这样:

            date     amplitude
id      
id1     2018-12-22  13532.650
id2     2018-04-17  12367.050
id3     2018-06-19  16291.375

谢谢

使用Index.get_level_values with Index.duplicated, inversing mask by ~ and filter by boolean indexing:

print (df)
             time_stamp  amplitude
id                                
id1 2018-06-19 00:36:00    16163.1
id1 2018-06-18 01:19:00    16399.7
id1 2018-06-18 01:24:00    16463.3
id1 2018-06-20 03:51:00    16139.4
id2 2018-03-17 03:41:00    11886.0
id2 2018-03-17 03:41:00    12293.6

#simplfying solution
av = df.groupby([df.index, df['time_stamp'].dt.date.rename('date')]).mean()
#alternative
#av = df.groupby([df.index, df['time_stamp'].dt.floor('d').rename('date')]).mean()
av = av[~av.index.get_level_values('id').duplicated(keep='last')]
print (av)
                amplitude
id  date           
id1 2018-06-20    16139.4
id2 2018-03-17    12089.8

如果将 MultiIndex 转换为列,请使用 DataFrame.drop_duplicates:

av = df.groupby([df.index, df['time_stamp'].dt.date.rename('date')]).mean().reset_index()

av = av.drop_duplicates('id', keep='last')
print (av)
    id        date  amplitude
2  id1  2018-06-20    16139.4
3  id2  2018-03-17    12089.8