gpt4 book ai didi

python - 如何根据条件从数据框中删除行

转载 作者:行者123 更新时间:2023-12-01 00:06:48 25 4
gpt4 key购买 nike

我有以下数据框(“ID”、“月份”和“状态”)。状态是关于“Churn”= 1 和“Not Churn”= 2。我想删除除第一次出现之外已流失的 ID 的所有行。例如:

数据框

    ID      Month   Status
2310 201708 2
2310 201709 2
2310 201710 1
2310 201711 1
2310 201712 1
2310 201801 1
2311 201704 2
2311 201705 2
2311 201706 2
2311 201707 2
2311 201708 2
2311 201709 2
2311 201710 1
2311 201711 1
2311 201712 1
2312 201708 2
2312 201709 2
2312 201710 2
2312 201711 1
2312 201712 1
2312 201801 1

删除后我应该有以下数据框

    ID      Month   Status
2310 201708 2
2310 201709 2
2310 201710 1

2311 201704 2
2311 201705 2
2311 201706 2
2311 201707 2
2311 201708 2
2311 201709 2
2311 201710 1

2312 201708 2
2312 201709 2
2312 201710 2
2312 201711 1

我尝试了以下操作 - 首先查找每个客户 ID 和 status=1 的最短日期

    df1=df[df.Status==1].groupby('ID')['Month'].min()

然后我必须删除状态 1 大于 MOnth 最小值的每个 ID 的所有行。

最佳答案

如果您熟悉DataFrame.idxmin要获取最近一个月的元素索引,您可以尝试:

# find minimum months
min_df = df.groupby(['ID','Status'])['Month'].idxmin().reset_index(drop=True)
# find indices of status 2 rows
df2 = df[df['Status'].eq(2)].index.to_series()
# append indices together
idx_df = min_df.append(df2).drop_duplicates()
# filter indices
df_new = df.iloc[idx_df].sort_index()
<小时/>
print(df_new)                                                                        
ID Month Status
0 2310 201708 2
1 2310 201709 2
2 2310 201710 1
6 2311 201704 2
7 2311 201705 2
8 2311 201706 2
9 2311 201707 2
10 2311 201708 2
11 2311 201709 2
12 2311 201710 1
15 2312 201708 2
16 2312 201709 2
17 2312 201710 2
18 2312 201711 1

更新

或者,您可以考虑使用 GroupBy.apply :

df1 = df.groupby(['ID','Status']).apply(lambda x: (x['Status'].eq(2)) | (x['Month'].eq(x['Month'].min())))
df1 = df1.reset_index(level=['ID','Status'], drop=True)
df_new = df.loc[df1]
<小时/>
print(df_new)                                                                                                                                              
ID Month Status
0 2310 201708 2
1 2310 201709 2
2 2310 201710 1
6 2311 201704 2
7 2311 201705 2
8 2311 201706 2
9 2311 201707 2
10 2311 201708 2
11 2311 201709 2
12 2311 201710 1
15 2312 201708 2
16 2312 201709 2
17 2312 201710 2
18 2312 201711 1

更新2

但是,如果您只是想删除最早月份行之后的所有状态 1 行,那么您可以简单地 sort_valuestransform :

df = df.sort_values(by=['ID','Month']).reset_index(drop=True) 
df = df[df.groupby('ID')['Status'].transform(lambda x: ~(x.duplicated() & (x == 1)))]
<小时/>
print(df)                                                              
ID Month Status
0 2310 201708 2
1 2310 201709 2
2 2310 201710 1
6 2311 201704 2
7 2311 201705 2
8 2311 201706 2
9 2311 201707 2
10 2311 201708 2
11 2311 201709 2
12 2311 201710 1
15 2312 201708 2
16 2312 201709 2
17 2312 201710 2
18 2312 201711 1

关于python - 如何根据条件从数据框中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59922516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com