Search code examples
pythonmatrixmatrix-multiplication

Python - Matrix Identity multiplication


I have a a dataframe a which is

a = [[3],
     [12],
     [15]]

and I want to turn it into

b = [[3, 0, 0],
     [0, 12,0],
     [0, 0, 15]]

It has been a while since high school and my matrix multiplication is a little off. Any help would be great.


Solution

  • You can use numpy functions

    >>> import numpy as np
    >>> import pandas as pd
    >>> b = np.zeros((3,3), dtype=int)
    >>> np.fill_diagonal(b, [3, 12, 15])
    >>> b
    array([[ 3,  0,  0],
           [ 0, 12,  0],
           [ 0,  0, 15]])
    

    If you need a DataFrame

    >>> pd.DataFrame(b)
       0   1   2
    0  3   0   0
    1  0  12   0
    2  0   0  15