从 python pandas groupby 中删除第一个和最后一个组

Remove first and last group from python pandas groupby

我有一些时间序列数据

time x   y
1s   34  8017  
1s   43  5019
1s   1   8017
2s   64  8870
2s   34  8305
2s   11  8305
3s   343 8221
3s   3   8221
3s   143 8221

我使用 python pandas groupbydf.groupby(data.index.second) 分组。生成 3 组,其中第 1 组看起来像这样,对应于第一秒

time x   y
1s   34  8017  
1s   43  5019
1s   1   8017

如何删除第一组(第 1 秒)和最后一组(第 3 秒)?

我只想要这组(第2组)

time x   y
2s   64  8870
2s   34  8305
2s   11  8305

我已经尝试 this 但没有成功,也许 groupby 函数不是正确的选择。

你可以这样做

df2 = df[df['time']=='2s']

这将从您的主 df 中删除 '1s''3s',然后我们可以将其存储在新变量中,我们都可以 df2

我通过保存所有密钥解决了这个问题

l = list(df.groupby(data.index.second))

然后从列表中删除第一个和最后一个键

del l[0]
del l[-1]

https://docs.python.org/3/library/stdtypes.html#dict

我注意到你回答了你自己的问题,但也许这有一些用处:使用 filter,

df.groupby('time').filter(lambda g: g.name not in ['1s','3s'])

生产

    time    x   y
3   2s     64   8870
4   2s     34   8305
5   2s     11   8305

您可以过滤 Series.isin with boolean indexing 中没有第一个和最后一个唯一值的所有唯一 time:

df = df[df['time'].isin(df['time'].unique()[1:-1])]
print (df)
  time   x     y
3   2s  64  8870
4   2s  34  8305
5   2s  11  8305

或更好的解决方案:

data = data.drop(data[data.timestamp.dt.second == data.iloc[0][0].second].index)
data = data.drop(data[data.timestamp.dt.second == data.iloc[-1][0].second].index)