2016-08-26 74 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