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

后端 未结 3 1731
无人及你
无人及你 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

    If a1 is a dataframe made of n columns and a2 is a another dataframe made by just 1 column, you can subtract a2 from each column of a1 using numpy

    np.subtract(a1, a2)
    

    You can achieve the same result if a2 is a Series making sure to transform to DataFrame

    np.subtract(a1, a2.to_frame()) 
    

    I guess that, before computing this operation, you need to make sure the indices in the two dataframes are coherent/overlapping. As a matter of fact, the above operations will work if a1 and a2 have the same number of rows and different indices. You can try

    a1 = pd.DataFrame([[1, 2], [3, 4]], columns=['a','b'])
    a2 = pd.DataFrame([[1], [2]], columns=['c'])
    
    np.subtract(a1, a2)
    

    and

    a1 = pd.DataFrame([[1, 2], [3, 4]], columns=['a','b'])
    a2 = pd.DataFrame([[1], [2]], columns=['c'], index=[3,4])
    
    np.subtract(a1,a2)
    

    will give you the same result.

    For this reason, to make sure the two DataFrames are coherent, you could preprocess using something like:

    def align_dataframes(df1, df2):
        r = pd.concat([df1, df2], axis=1, join_axes=[df1.index])
        return r.loc[:,df1.columns], r.loc[:,df2.columns]
    

提交回复
热议问题