我还不习惯 python、numpy 或 pandas。但是我正在研究类似问题的解决方案,所以让我以这个问题为例报告我的答案。
import pandas as pd
df = pd.DataFrame()
df['name'] = ['foo', 'foo', 'bar', 'bar', 'foobar', 'foobar']
df['time'] = [5, 2, 5, 6, 20, 1]
grouped = df.groupby('name')
for k, group in grouped:
print(group)
我的答案1:
indexes_should_drop = grouped.filter(lambda x: (x['time'].max() <= 5)).index
result1 = df.drop(index=indexes_should_drop)
我的答案2:
filter_time_max = grouped['time'].max() > 5
groups_should_keep = filter_time_max.loc[filter_time_max].index
result2 = df.loc[df['name'].isin(groups_should_keep)]
我的答案3:
filter_time_max = grouped['time'].max() <= 5
groups_should_drop = filter_time_max.loc[filter_time_max].index
result3 = df.drop(df[df['name'].isin(groups_should_drop)].index)
结果
name time
2 bar 5
3 bar 6
4 foobar 20
5 foobar 1
积分
My Answer1 不使用组名来删除组。如果您需要组名,您可以通过以下方式获取:df.loc[indexes_should_drop].name.unique()。
grouped['time'].max() <= 5 和 grouped.apply(lambda x: (x['time'].max() <= 5)).index 返回相同的结果。
filter_time_max 的索引是组名。它不能用作索引或标签以按原样删除。
name
foo True
bar False
foobar False
Name: time, dtype: bool