Suppose I have 2 pandas series, a and b, where the elements are matrices as follows
a = pd.Series([np.array([[1,2], [3,4]]), np.array([[1,2], [3,4]])])
b = pd.Series([np.array([[1,2], [3,4]]), np.array([[1,2], [3,4]])])
I would like to multiply the series elements of a with b such that the output looks like:
output of series multiplication
I have the following solution which works:
c = []
for i in range(a.shape[0]):
c.append(np.matmul(a[i], b[i]))
however, this requires a for loop and outputs a list rather than a .Series. Any ideas how this could be done in a more compact form? Thanks.
CodePudding user response:
IIUC use:
c = []
for i in range(a.shape[0]):
c.append(np.matmul(a[i], b[i]))
print (pd.Series(c))
0 [[7, 10], [15, 22]]
1 [[7, 10], [15, 22]]
dtype: object
Or:
print (pd.Series([np.matmul(a[i], b[i]) for i in range(a.shape[0])]))
0 [[7, 10], [15, 22]]
1 [[7, 10], [15, 22]]
dtype: object
CodePudding user response:
Just convert the list to pandas Series and print. Add the following code at the end:
print(pd.Series(c))
CodePudding user response:
I couldn't figure out how to do it in pandas, but it's so much easier if you convert those Series to numpy arrays.
pd.Series(list(np.matmul(np.array(a.to_list()), np.array(b.to_list()))))
