Search code examples
pythonpandasdataframecalculated-columnsdifference

How can I create a new dataframe by subtracting the first column from every other column?


import pandas as pd
df = {'a': [1,1,1], 'b': [3,3,3,], 'c': [5,5,5,], 'd': [7,7,7], 'e': [9,9,9]}
df1 = pd.DataFrame(df, columns = ['a', 'b', 'c', 'd', 'e'])
dg = {'b': [2,2,2], 'c': [4,4,4], 'd': [6,6,6], 'e': [8,8,8]}
df2 = pd.DataFrame(dg, columns = ['b', 'c', 'd', 'e'])
df1
    a   b   c   d   e
0   1   3   5   7   9
1   1   3   5   7   9
2   1   3   5   7   9

df1 is my original dataframe. I want to create another dataframe by substracting column a from every other column (taking the difference between column a and all other columns).

df2
    b   c   d   e
0   2   4   6   8
1   2   4   6   8
2   2   4   6   8

df2 is the outcome.

I would appreciate your help.


Solution

  • df = df1.loc[:,'b':].apply(lambda x: x-df1['a'])
    print(df)
    

    Prints:

       b  c  d  e
    0  2  4  6  8
    1  2  4  6  8
    2  2  4  6  8