2016-04-22 33 views
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. 

有谁知道如何修改它?提前致谢!

回答

2

更新: - 从@root更优雅的解决方案(一衬垫):

In [131]: df['C'] = (df.A.shift(-1).sub(df.A, fill_value=0)/df.B.shift(-1).sub(df.B, fill_value=0)).round(2).astype(str) 

In [132]: df 
Out[132]: 
    A B  C 
0 1 2 2.0 
1 3 3 1.33 
2 7 6 0.75 
3 13 14 0.93 

In [133]: df.dtypes 
Out[133]: 
A  int64 
B  int64 
C object 
dtype: object 

你能做到这样:

df['C'] = (df.A.shift(-1) - df.A)/(df.B.shift(-1) - df.B) 
df.loc[df.index.max(), 'C'] = df.loc[df.index.max(), 'A']/df.loc[df.index.max(), 'B'] 
df.round(2) 

产量:

In [118]: df.round(2) 
Out[118]: 
    A B  C 
0 1 2 2.00 
1 3 3 1.33 
2 7 6 0.75 
3 13 14 0.93 
+2

您可以使用'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

+0

@root,yes,确实 - 它更优雅,谢谢你!我已经更新了答案 – MaxU

+0

没问题。我有一个更好的解决方案,使用'fill_value',但没有看到好的解决方案,直到我看到你的答案! – root