Subtract one dataframe from another excluding the first column Pandas

后端 未结 3 1635
说谎
说谎 2021-01-27 17:22

I have to dataframes with the same columns. My task should be to subtract the df_tot from df_nap without touching the first column (\'A\'). What is the easiest solution for it?<

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-27 17:59

    Simply subtract the entire DataFrames, then reassign the desired values to the Wavelength column.

    result = df_tot - df_nap
    result['Wavelength'] = df_tot['Wavelength']
    

    For example,

    import numpy as np
    import pandas as pd
    
    df_tot = pd.DataFrame(np.random.randint(10, size=(3,4)), columns=list('ABCD'))
    df_nap = pd.DataFrame(np.random.randint(10, size=(3,4)), columns=list('ABCD'))
    # df_tot['A'] = df_nap['A']   # using column A as the "Wavelength" column
    
    result = df_tot - df_nap
    result['A'] = df_tot['A']
    

    Alternatively, or if Wavelength column were not numeric, you could subtract everything except the Wavelength, then reassign that column:

    result = df_tot.drop('Wavelength', axis=1) - df_nap.drop('Wavelength', axis=1)
    result['Wavelength'] = df_tot['Wavelength']
    

提交回复
热议问题