【发布时间】:2020-10-27 21:26:23
【问题描述】:
我想比较两列中的两个连续行,如果它们的值相同,则根据第三列值之间的差异创建一个新列。请参阅下面的输入和预期输出:
输入:
df = pd.Dataframe({'Account Number': [123,123,123,456,456,456], 'Value':['ABC', 'ABC', 'ABC', 'DEF', 'DEF', 'DEF'],'Positions':[10,10,20,20,20,15]})
预期输出:
df = pd.Dataframe({'Account Number': [123,123,123,456,456,456],'Value':['ABC', 'ABC', 'ABC', 'DEF', 'DEF', 'DEF'],'Positions':[10,10,20,20,20,15], 'new_col': [0,0,10,0,0,-5]})
在excel中,公式很简单:
IF(AND(B2=B1,C2=C1), D2-D1, 0)
其中:B = 帐号,C = 价值,D = new_col
到目前为止,我已经尝试了两次尝试 - (1) 使用 iloc(这会产生 IndexError: Single positional indexer is out of bounds")和 (2) 使用 rolling(n) - 但我不能甚至编译。请参阅下面我在 (1) 处的尝试,任何帮助都会很棒。谢谢!
a = 0
if a != len(df):
for a in range(len(df)):
df['new_col'] = np.where((df["Account Number"].iloc[a+1] == df["Account Number"].iloc[a]) and (df["Value"].iloc[a+1] == df["Value"].iloc[a]), df["Positions"].iloc[a+1] df["Positions"].iloc[a], 0)
a+= 1
【问题讨论】:
标签: python pandas dataframe window-functions