0

Hi I'm trying to subtract values of one of DataFrame columns from whole DataFrame. Intuitively this seems like a non-problem for me, but somehow I can't figure it out.

Here is the code:

import pandas as pd

x = pd.DataFrame({
    "a": range(1, 10),
    "b": range(2, 11),
    "c": range(11, 20)
})

print x - x['b']

And what I get is surprisingly:

    0   1   2   3   4   5   6   7   8   a   b   c
0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
3 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
5 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
6 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
7 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
8 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

Instead of DataFrame with columns: (a-b), (b-b), (c-b).

I just started playing with Python. Can you tell me what am I missing?

Thanks!

Stefan
  • 41,759
  • 13
  • 76
  • 81
  • You may want to see my answer here which shows what's happening: http://stackoverflow.com/questions/29954263/what-does-the-term-broadcasting-mean-in-pandas-documentation/29955358#29955358 – EdChum Jan 12 '16 at 21:56

1 Answers1

2

Try:

x.subtract(x['b'], axis=0)

   a  b  c
0 -1  0  9
1 -1  0  9
2 -1  0  9
3 -1  0  9
4 -1  0  9
5 -1  0  9
6 -1  0  9
7 -1  0  9
8 -1  0  9

See docs for details on the axis=0 parameter, which ensures that the index of x['B'] aligns with the DataFrame index, and not the columns as per default.

To make the - operator work, you'd have to:

(x.T - x['b']).T
Stefan
  • 41,759
  • 13
  • 76
  • 81