将 df1 中所有列的值减去 df2 中一列中的值

Jyo*_*hsa -2 python pandas

假设我有以下数据框df1

 a    b    c    d
 10   15   20   25
 8    18   28   38
 20   25   30   35
Run Code Online (Sandbox Code Playgroud)

为简单起见,假设我有一个数据集df2

 y
 1
 2
 3
Run Code Online (Sandbox Code Playgroud)

我想df2从中的值中逐行减去中的值df1

因此,我的最终数据集df3= df1-df2将是:

  a    b    c    d
  9   14   19   24
  6   16   26   36
 17   22   27   32
Run Code Online (Sandbox Code Playgroud)

raf*_*elc 5

使用subaxis=0用于矢量化解决方案

df.sub(df2.values, axis=0)
Run Code Online (Sandbox Code Playgroud)
    a   b   c   d
0   9  14  19  24
1   6  16  26  36
2  17  22  27  32
Run Code Online (Sandbox Code Playgroud)

Timings

对于少量列:

%timeit (df.sub(df2.values, axis=0))
784 µs ± 15.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit df.apply(lambda x: x - df2['y'])
2.22 ms ± 70.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Run Code Online (Sandbox Code Playgroud)