Search code examples
pythonpandasnumpyadditionsubtraction

Pandas values substituted by numpy matrix?


My question is very simple. I have a dataFrame and I want to add or substract my DataFrame by a numpy matrix. The size of the two matrix are identical. I would like this kind of things : my_matrix.values = my_matrix.values + numpy_matrix, or my_matrix.values = my_matrix.values - numpy_matrix, very efficiently.

Is not possible? Because the size of ma matrix is quite huge and the "update", subtract or the "add" command is quite long. Is it better to recreate a DataFrame each time?


Solution

  • IIUC, something like this:

    df = pd.DataFrame([[1,2],[3,4]],columns=['A','B'])
    my_arr = np.array([[2,2],[2,2]])
    
    df += my_arr
    
    print(df)
    

    Output:

       A  B
    0  3  4
    1  5  6