Ramesh-X - 8 months ago 51

Python Question

For some work that I am doing recently, I need the following operation to be done.

`def myfunc(a, b):`

return a*b # some operation here

a = [1,2,3]

b = [2,4,6,8]

print [[myfunc(i, j) for i in a] for j in b]

I need to create a 2D array from 1D arrays as shown above.

Can someone please tell me a way to do this using

`numpy`

The arrays

`a`

`b`

Answer

You can use numpy broadcasting:

```
a = np.array([1,2,3])
b = np.array([2,4,6,8])
a = a[:, None]
b = b[None, :]
a * np.log(a/b)
```

adding a new axis to `a`

and `b`

(as second and first axis respectively) will make `a`

's shape `(3, 1)`

and `b`

's shape `(1, 4)`

. Then, `a/b`

a 2D `(3, 4)`

array where the `i`

-th column is `a[i]/b`

:

```
a/b
array([[ 0.5 , 0.25 , 0.16666667, 0.125 ],
[ 1. , 0.5 , 0.33333333, 0.25 ],
[ 1.5 , 0.75 , 0.5 , 0.375 ]])
```

Then you can take the pointwise log and multiply by `a`

. Since `np.log(a/b)`

is (3, 4) and `a`

is (3, 1), `a`

will again be broadcasted to (3, 4).

A small subtlety is that, due to the way broadcasting happens, adding the second axis to `b`

is not mandatory. I prefer writing it out explicitly nevertheless, for clarity.

Source (Stackoverflow)