groupby 分组,保留组内符合条件的数据
以下是根据投保单号进行分组,保留组内质检次数最大的一条数据
import pandas as pd
df = pd.read_excel('baoxian.xlsx', dtype=str)
# 获取分组内质检次数最大的数据
df = df.groupby('投保单号').apply(lambda x : x[x['质检次数'] == x['质检次数'].max()])
# 过滤一次性通过的保单
df = df[(df['质检次数'] == '1') & (df['质检状态'] == '已质检') & (df['质检结论'] == '通过')]
groupby分组,根据特定条件排序,保留第一条数据
- pandas实现方法
def get_max_month_traget(x):
"""获取最大值的那一行"""
df = x.sort_values(by='month_target', ascending=False)
return df.iloc[0, :]
e11 = e1.groupby(["key_customer", "cycle_no"], as_index=False).apply(get_max_month_traget)
- sql 实现方法
select *
from(select
*,ROW_NUMBER() over (partition by key_customer,cycle_no order by month_traget desc) as contract_long_rn
from tdm_vitality_buchong_2
)t
where contract_long_rn = 1
cut分桶
例如根据单品销售价格 分为 [“0-1”, “1-3”, “3-5”, “5-10”, “10以上”]
df["单品销售价格段"] = pd.cut(df["单品销售价格"], bins=[0, 1, 3, 5, 10, 500], labels=["0-1", "1-3", "3-5", "5-10", "10以上"])