Subtract a Series from a DataFrame while keeping the DataFrame struct intact

后端 未结 3 1733
无人及你
无人及你 2020-12-10 15:05

How can I subtract a Series from a DataFrame, while keeping the DataFrame struct intact?

df = pd.DataFrame(np.zeros((5,3)))
s = pd.Series(np.ones(5))

df - s         


        
3条回答
  •  清歌不尽
    2020-12-10 16:09

    I'll throw in an example that modifies a subset of the a DataFrame

    df = pd.DataFrame(np.arange(20).reshape((2,10)),columns=list('abcdefghjk'))
    
    >>> df
        a   b   c   d   e   f   g   h   j   k
    0   0   1   2   3   4   5   6   7   8   9
    1  10  11  12  13  14  15  16  17  18  19
    
    # Series to be subtracted    
    dif = df['g'] - df['h']
    
    >>> dif
    0   -1
    1   -1
    dtype: int32
    
    # subtract the Series from columns 'g','h','j','k'
    df.loc[:,'g':] = df.loc[:,'g':].subtract(dif,axis='rows')
    #df.loc[:,'g':] = df.loc[:,'g':].subtract(dif,axis=0)
    
    >>> df
        a   b   c   d   e   f   g   h   j   k
    0   0   1   2   3   4   5   7   8   9  10
    1  10  11  12  13  14  15  17  18  19  20
    

提交回复
热议问题