我有一個數據幀df
是像這樣定義:以更有效的方式後續行之間的應用功能與熊貓
import numpy as np
import pandas as pd
dic = {'A':['1A','1A','3C','3C','3C','7M','7M','7M'],'B':[10,15,49,75,35,33,45,65],'C':[11,56,32,78,45,89,15,14],'D':[111,0,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan],'E':[0,222,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]}
df = pd.DataFrame(dic)
我的目標是具有A
列在同一項目行之間進行一些計算。
的函數被定義爲是這樣的(但可以是任何東西):
def fun(a,b,c,d):
out = a*c + b/2 + d*b
return out
這樣的操作的結果將根據以下規則被存儲在列d和E:
# Fill column D
for j in range(0,len(df)-1):
if df['A'].iloc[j]==df['A'].iloc[j+1] and pd.isnull(df['D'].iloc[j]):
df['D'].iloc[j] = fun(df['B'].iloc[j],df['B'].iloc[j],df['B'].iloc[j+1],df['B'].iloc[j+1])
# Fill column E
for j in reversed(range(1,len(df))):
if df['A'].iloc[j-1]==df['A'].iloc[j] and pd.isnull(df['E'].iloc[j]):
df['E'].iloc[j] = fun(df['B'].iloc[j],df['B'].iloc[j],df['B'].iloc[j-1],df['B'].iloc[j-1])
兩個循環非常相似,但第二個循環是從最後一個元素循環到第一個數據幀。 我的代碼工作正常,結果應該是這樣的:
# Before # # After #
A B C D E A B C D E
0 1A 10 11 111 0 0 1A 10 11 111.0 0.0
1 1A 15 56 0 222 1 1A 15 56 0.0 222.0
2 3C 49 32 NaN NaN 2 3C 49 32 7374.5 NaN
3 3C 75 78 NaN NaN 3 3C 75 78 5287.5 7387.5
4 3C 35 45 NaN NaN 4 3C 35 45 NaN 5267.5
5 7M 33 89 NaN NaN 5 7M 33 89 2986.5 NaN
6 7M 45 15 NaN NaN 6 7M 45 15 5872.5 2992.5
7 7M 65 14 NaN NaN 7 7M 65 14 NaN 5882.5
你能夠改善這樣的代碼,以便在使用某些功能構建從熊貓庫使其更有效率?我想有一些更優雅的方式來實現我的結果。
注意:第一行和第二行已經值(111 0
和0 222
),因此它們不能被函數來計算!
嘗試使用Series.diff – yuval
@ user2476373感謝您的評論:)你能提供給我關於如何使用它更多的細節和爲什麼它是合適的對於我的問題? –