我有一个数据帧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感谢您的评论:)你能提供给我关于如何使用它更多的细节和为什么它是合适的对于我的问题? –