0
我有一个示例数据框,如下所示。我想进行计算,然后将结果作为新列附加到当前数据框。将相应的列连接到数据框熊猫
A, B # this is my df, a csv file
1, 2
3, 3
7, 6
13, 14
下面是我尝试过的一些代码。
for i in range(0,len(df.index)+1,1):
if len(df.index)-1 == i:
df['C'] = str(df.iloc[i]['A']/df.iloc[i]['B'])
else:
df['C'] = str((df.iloc[i+1]['A'] - df.iloc[i]['A'])/(df.iloc[i+1]['B'] - df.iloc[i]['B'])) # I need string as dtype
df.to_csv(Out, index = False)
这只给我最终循环的结果,而不是相应的结果取决于每个计算。
A B C
1 2 2
3 3 1.33
7 6 0.75
13 14 0.93 # It is the result I'd like to see.
有谁知道如何修改它?提前致谢!
您可以使用'sub'而不是减号,并提供关键字参数'fill_value = 0'来完成一行。例如'df.A.shift(-1).sub(df.A,fill_value = 0)/(df.B.shift(-1).sub(df.B,fill_value = 0)' – root
@root,yes,确实 - 它更优雅,谢谢你!我已经更新了答案 – MaxU
没问题。我有一个更好的解决方案,使用'fill_value',但没有看到好的解决方案,直到我看到你的答案! – root