python - 减去两个不同大小的数据帧,但至少保持第一个数据帧的大小

标签 python pandas dataframe subtraction

我有一个 DataFrame df,我想从那里减去 df2。

需要注意的是,我希望 df 保持相同的大小,对于 df 中的每个元素,我想减去 df2(如果 df2 中没有这样的唯一索引/列),它只是 df (i,j) - 0(因为在 df2 中找不到这样的索引/列)。

例子:

df:

Date    Blue    Dog Apple
1/1/2016    3   4   2
1/1/2015    3   4   2
1/1/2014    3   4   2
1/1/2013    3   4   2
1/1/2013    3   4   2
1/1/2013    3   4   2

df2:

Date    Apple   Blue    Cat
1/1/2017    1   3   2
1/1/2016    1   3   2
1/1/2015    1   3   2
1/1/2014    1   3   2

我希望 df - df2 看起来像这样:

Date    Blue    Dog Apple
1/1/2016    0   4   1
1/1/2015    0   4   1
1/1/2014    0   4   1
1/1/2013    3   4   2
1/1/2012    3   4   2
1/1/2011    3   4   2

谢谢。

最佳答案

填补空白:

(df-df2).combine_first(df).reindex_like(df).astype(int)
Out[45]: 
          Blue  Dog  Apple
Date                      
1/1/2016     0    4      1
1/1/2015     0    4      1
1/1/2014     0    4      1
1/1/2013     3    4      2
1/1/2012     3    4      2
1/1/2011     3    4      2

关于python - 减去两个不同大小的数据帧,但至少保持第一个数据帧的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42542026/

相关文章:

python - 在 Ubuntu 中安装 Theano 的问题

python - ogr 中 SetField/SetFeature 的段错误(核心转储)

Python 网络带宽监视器

python-2.7 - 将列设置为索引时 Dtype 发生变化

python - 提取 Excel 值并将其放入列表中

python - pandas drop_duplicates 并保留最接近引用时间的值

r - 使用 grep 对数据框进行子集化

python - numpy 3 维数组中间索引错误

python - 检查 Pandas 中任何列的任何行中是否存在一个值?

r - 在 R 中创建组合数据框