我有以下数据框.
df = pd.DataFrame(
{
"drive": [1,1,2,3,4,5,6,7,7],"team": ['home','home','away','home'],"home_comfy_lead": [0,1],"home_drives": [1,4],'home_drives_with_comfy_lead': [0,3]
})
我正在尝试制作两列:
> home_drives列,该列唯一地计算来自
车队依据车队的“主场”称号
柱.
>一个home_drives_with_comfy_lead列,该列唯一地计算
home_drives根据home_comfy_lead是否为true来驱动值.
我想要的输出是:
drive team home_comfy_lead home_drives home_drives_with_comfy_lead
0 1 home 0 1 0
1 1 home 0 1 0
2 2 away 0 0 0
3 2 away 0 0 0
4 2 away 0 0 0
5 3 home 0 2 0
6 3 home 0 2 0
7 3 home 1 2 1
8 4 away 0 0 0
9 4 away 0 0 0
10 4 away 0 0 0
11 5 home 1 3 2
12 5 home 1 3 2
13 6 away 0 0 0
14 6 away 0 0 0
15 7 home 1 4 3
16 7 home 1 4 3
有人能帮忙吗?我已经为此苦苦挣扎了几天.
最佳答案
使用.where屏蔽,然后使用groupby ngroup.在这里,我们很幸运为NaN组分配了-1,并且您还想从1开始计数,因此同时添加了两个固定值.
原文链接:https://www.f2er.com/python/533116.htmldf['home_drives'] = df.where(df.team == 'home').groupby('drive').ngroup()+1
df['hdwcl'] = df.where(df.home_comfy_lead == 1).groupby('home_drives').ngroup()+1
输出:
drive team home_comfy_lead home_drives hdwcl
0 1 home 0 1 0
1 1 home 0 1 0
2 2 away 0 0 0
3 2 away 0 0 0
4 2 away 0 0 0
5 3 home 0 2 0
6 3 home 0 2 0
7 3 home 1 2 1
8 4 away 0 0 0
9 4 away 0 0 0
10 4 away 0 0 0
11 5 home 1 3 2
12 5 home 1 3 2
13 6 away 0 0 0
14 6 away 0 0 0
15 7 home 1 4 3
16 7 home 1 4 3