【问题标题】:pandas: all NaNs when subtracting two dataframespandas:减去两个数据帧时的所有 NaN
【发布时间】:2017-01-03 08:10:15
【问题描述】:

我有两个系列。我想从另一个数据帧中减去一个数据帧,即使它们的列数不同。

>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

我假设减去两个具有不同维度的数据框只会导致不匹配的列(在本例中为 0 列)中出现 NaN。其余列将是 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。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您正在减去两个数据帧。 列索引和行索引必须匹配。在您的情况下,行索引 TOTALUse 不匹配。

    要得到你要找的东西,你想从df1 中减去系列df2.ix['Use']

    df1.sub(df2.squeeze())
    

    或者:

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

    或者:

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

    或者:

    df1 - df2.ix['Use']
    

    或者:

    df1 - df2.loc['Use']
    

    【讨论】:

    • 谢谢! Squeeze() 解决方案完美运行。我知道列索引必须匹配,但没有意识到行索引也必须匹配。
    【解决方案2】:

    由于两个数据帧需要有相同的索引,所以你可以重置索引,然后对数据帧执行减法。

    使用这个然后执行减法:

    df1.reset_index(inplace=True)
    df2.reset_index(inplace=True)
    

    一旦索引重置为默认值,您就可以执行减法/加法或任何操作。

    df1-df2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 2017-08-07
      • 1970-01-01
      • 2021-08-17
      • 2019-06-13
      • 1970-01-01
      相关资源
      最近更新 更多