为什么循环在计算时会产生NaN值?

时间:2020-04-07 11:04:50

标签: python pandas

我有两个数据框:

d = {'ID': ['ID1', 'ID2', 'ID3'], 'Count': [24, 98, 115]}
df1 = pd.DataFrame(data=d)

d = {'ID': ['ID1', 'ID2', 'ID3'], 'Val1': [3, 23, 45], 'Val2': [64, 23, 34], 'Val3': [343, 112, 545]}
df2 = pd.DataFrame(data=d)

FOR each ID I want to calculate the Result by the next formula:  

RES1 = df1['Count'] + 1 - df2['Val1']
RES2 = RES1 + 1 - df2['Val2']
RES3 = RES2 + 1 - df2['Val3']

我创建了一个用于迭代和获取所需值的循环,但是会产生错误。

tt = list(set(df1.ID).intersection(set(df2.ID)))
appended_data = []  
for t in tt:
df3 = pd.DataFrame()
df3['ID']= t
for k in range(1,4):
    if k==1:
        df3['RES'+ str(k)]=df1[df1.ID==str(t)]['Count'] + 1 - df2.iloc[(df2.iloc[:, 0] == str(t)).values, k].astype(int)
    else:
        df3[k]=df3[df3[k-1]] + 1 - df2.iloc[(df2.iloc[:, 0] == str(t)).values, k].astype(int)
    appended_data.append(onhand_loc)

预期输出如下:

ID | RES1 | RES2 | RES3  |
ID1| 22   | -41  | -383  |  
ID2| 76   | 54   | -57   |  
ID3| 71   | 38   | -506  |  

1 个答案:

答案 0 :(得分:2)

不确定这是否是您的目标:

(df1.join(df2)
 .assign(RES1 = lambda x: x.Count.add(1).sub(x.Val1),
         RES2 = lambda x: x.RES1.add(1).sub(x.Val2),
         RES3 = lambda x: x.RES2.add(1).sub(x.Val3)
        )
 .filter(like='RES')
 .reset_index()
)

    ID  RES1    RES2    RES3
0   ID1 22       -41    -383
1   ID2 76        54    -57
2   ID3 71        38    -506