2016-08-26 75 views
4

我有兩個系列。我想從另一個數據幀中減去一個數據幀,即使它們有不同數量的列。熊貓:減去兩個數據幀時的所有NaN

>df1 

index 0 1 2 3 4 5 
TOTAL 5 46 56 110 185 629 

>df2 
index 1 2 3 4 5 
Use  25 37 86 151 512 

我假設減去2個dataframes具有不同尺寸的將結果的NaN在不匹配的列(在這種情況下,列0)。剩餘的列將是DF1的結果[1] -df2 [1],DF1 [2] -df2 [2]等

>df1 - df2 
index 0 1 2 3 4 5 
TOTAL NaN 21 19 24 34 117 

但這並非如此。當我減去數據幀時會發生什麼?

>df1 - df2 
index 0 1 2 3 4 5 
Use  NaN NaN NaN NaN NaN NaN 
TOTAL NaN NaN NaN NaN NaN NaN 

我也試過只是減去值:

>df1.values - df2.values 
Traceback (most recent call last): 

    File "<ipython-input-376-1dc5b3b4ad3e>", line 1, in <module> 
    total_drugs.values-(restraints_drugs.values+norestraints_drugs.values) 

ValueError: operands could not be broadcast together with shapes (1,6) (1,5) 

我在做什麼錯?我使用的是熊貓0.18。

回答

2

您正在減去兩個數據幀。 列和行索引必須匹配。在你的情況下,行索引TOTALUse不匹配。

爲了讓你在找什麼,你想從df1

df1.sub(df2.squeeze()) 

enter image description here

或減去該系列df2.ix['Use']

df1.sub(df2.ix['Use']) 

或者:

df1.sub(df2.loc['Use']) 

或者:

df1 - df2.ix['Use'] 

或者:

df1 - df2.loc['Use'] 
+0

謝謝! squeeze()解決方案完美運作。我知道列索引必須匹配,但沒有意識到行索引必須匹配。 – ale19