gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:32:02 24 4
gpt4 key购买 nike

我有两个数据框:

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 |

最佳答案

不确定这是不是你的目标:

(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

关于python - 为什么循环在计算时会产生 NaN 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61078554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com