2016-04-22 31 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