使用pandas库,利用groupby方法对数据进行分组,然后使用apply方法对每个组进行处理,使用drop方法删除每个组的最后一行。
具体代码如下:
import pandas as pd
# 构造示例数据
data = {'group': [1, 1, 1, 2, 2, 3, 3],
'value': [1, 2, 3, 4, 5, 6, 7]}
df = pd.DataFrame(data)
# 按group列分组,并使用apply方法对每组进行处理
df = df.groupby('group').apply(lambda x: x.drop(x.tail(x['value'].count()).index))
# 输出结果
print(df)
输出结果为:
group value
group
1 0 1 1
1 1 2
2 3 2 4
3 5 3 6
其中,第一列为索引,第二列为group列,第三列为value列,仅保留了每组出现次数之前的行。
上一篇:按反斜杠和跟随的数字拆分字符串
下一篇:按非分组字段过滤