[英]Pandas how to apply a function to groupby().first()
我有一個 df,代碼是:
df = """
ValOption RB test contrat
0 SLA 4 3 23
1 AC 5 4 12
2 SLA 5 5 23
3 AC 2 4 39
4 SLA 5 5 26
5 AC 3 4 52
6 SLA 4 3 64
0 SLA 4 3 23
1 AC 5 4 12
2 SLA 5 5 23
3 AC 2 4 39
4 SLA 5 5 26
5 AC 5 4 52
6 SLA 4 3 64
"""
df = pd.read_csv(StringIO(df.strip()), sep='\s+')
output:
ValOption RB test contrat
0 SLA 4 3 23
1 AC 5 4 12
2 SLA 5 5 23
3 AC 2 4 39
4 SLA 5 5 26
5 AC 3 4 52
6 SLA 4 3 64
0 SLA 4 3 23
1 AC 5 4 12
2 SLA 5 5 23
3 AC 2 4 39
4 SLA 5 5 26
5 AC 5 4 52
6 SLA 4 3 64
現在我將它分組並通過以下方式獲得第一個:
df_u=df.groupby(['RB','test']).first()
output:
然后我想對每一行應用 function,出於某種原因我必須使用 pd.apply() function:
def func(row):
v1=row['RB']*3
v2=row['test']-1
return v1+v2
df_u['new_col']=df_u.apply(lambda row:func(row), axis=1)
注意:在實際業務中function很復雜很長,需要使用pd.apply()
然后我得到一個錯誤:
KeyError: ('RB', 'occurred at index (2, 4)')
您必須reset_index
才能訪問“RB”和“測試”行。 使用.values
將值設置為new_col
:
df_u['new_col'] = df_u.reset_index().apply(func, axis=1).values
print(df_u)
# Output:
ValOption contrat new_col
RB test
2 4 AC 39 9
3 4 AC 52 12
4 3 SLA 23 14
5 4 AC 12 18
5 SLA 23 19
更新
如何將 new_col 返回到原來的 df?
df = df.merge(df.drop_duplicates(['RB', 'test'])
.assign(new_col=func)[['RB', 'test', 'new_col']],
on=['RB', 'test'], how='left')
# Output
ValOption RB test contrat new_col
0 SLA 4 3 23 14
1 AC 5 4 12 18
2 SLA 5 5 23 19
3 AC 2 4 39 9
4 SLA 5 5 26 19
5 AC 3 4 52 12
6 SLA 4 3 64 14
7 SLA 4 3 23 14
8 AC 5 4 12 18
9 SLA 5 5 23 19
10 AC 2 4 39 9
11 SLA 5 5 26 19
12 AC 5 4 52 18
13 SLA 4 3 64 14
更新2
我 drop_duplicates 的原因是為了節省時間,讓它更快,因為行的長度是 60k,如果我應用到每一行,它會花費很多時間,而不是如果我先刪除重復的,我不需要應用到每一行row,我直接給同列值行賦值
Apply 是一個 for 循環,使用矢量化:
df['new_col'] = (df['RB']*3) + (df['test']-1)
表現
對於 140,000 條記錄,上述操作耗時 361 微秒:
%timeit (df1['RB']*3) + (df1['test']-1)
361 µs ± 9.02 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
對於 14 條記錄(這不是錯誤),之前的操作耗時 935 µs:
%timeit df.drop_duplicates(['RB', 'test']).apply(func, axis=1)
935 µs ± 5.44 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.