Home > Software design >  How can you multiply all the values within a 2D df with all the values within a 1D df separately?
How can you multiply all the values within a 2D df with all the values within a 1D df separately?

Time:12-27

I'm new to numpy and I'm currently working on a modeling project for which I have to perform some calculations based on two different data sources. However until now I haven't managed to figure out how I could multiply all the individual values to each other:

I have two data frames

One 2D-dataframe:

df1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

One 1D-dataframe:

df2 = np.array([1, 2, 3, 4, 5])

I would like to multiply all the individual values within the first dataframe (df1) separately with all the values that are stored within the second dataframe in order to create a data cube / new 3D-dataframe that has the shape 5x3x3:

df3 = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[2, 4, 6], [8, 10, 12], [14, 16, 18]], ..... ])

I tried different methods but every time I failed to obtain something that looks like df3.

x = np.array([[1, 2, 3],
     [4, 5, 6],
    [7, 8, 9]])
y = np.array([1, 2, 3, 4, 5])



z = y


for i in range(len(z)):
    z.iloc[i] = x

for i in range(0, 5):
    for j in range(0, 3):
        for k in range(0, 3):
            z.iloc[i, j, k] = y.iloc[i] * x.iloc[j, k]

print(z)

Could someone help me out with some example code? Thank you!

CodePudding user response:

Try this:

df1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df2 = np.array([1, 2, 3, 4, 5])

df3 = df1 * df2[:, None, None]

Output:

>>> df3
array([[[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9]],

       [[ 2,  4,  6],
        [ 8, 10, 12],
        [14, 16, 18]],

       [[ 3,  6,  9],
        [12, 15, 18],
        [21, 24, 27]],

       [[ 4,  8, 12],
        [16, 20, 24],
        [28, 32, 36]],

       [[ 5, 10, 15],
        [20, 25, 30],
        [35, 40, 45]]])
  • Related