I have some data frame 'A' like this (I think this is pandas series):
1
2
3
4
and another data set 'B' looks like this (this is I think numpy.ndarray):
[5 4 3 2 1]
I am trying to multiply first element from 'A' with all elements from 'B', second element from 'A' with all elements from 'B' ..... so at the end I will have something like this:
5 4 3 2 1
10 8 6 4 2
15 12 9 6 3
20 16 12 8 4
I would like to avoid using any loop here if this is possible.
Any suggestion or advices .... Thanks.
CodePudding user response:
Use numpy broadcasting:
s = pd.Series(range(1,5))
a = np.array([5, 4, 3, 2, 1])
out = s.to_numpy()[:, None] * a
print (out)
[[ 5 4 3 2 1]
[10 8 6 4 2]
[15 12 9 6 3]
[20 16 12 8 4]]
If need DataFrame:
df = pd.DataFrame(out)