Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cartesian product from two Series, different lengths and indexes

Given two series:

import pandas as pd
ser1 = pd.Series(data = [1,2,3], index=[1,2,3])
ser2 = pd.Series(data = [1,2,3,4,5], index = ['a','b','c','d','e'])

How can I cross-multiply the two to get this desired output?

pd.DataFrame(
data = [[1,2,3],[2,4,6],[3,6,9],[4,8,12],[5,10,15]],
index = ser2.index,
columns = ser1.index,)

My approach so far has been to build a temporary dataframe with index and cols matching the two series, and then iterate over one of the two series using iteritems(). I feel like there should be a cleaner way to achieve this.

like image 280
ac24 Avatar asked Dec 10 '22 06:12

ac24


1 Answers

I think need numpy.outer for outer product of two Series:

df = pd.DataFrame(np.outer(ser2, ser1), index = ser2.index, columns = ser1.index)

print (df)
   1   2   3
a  1   2   3
b  2   4   6
c  3   6   9
d  4   8  12
e  5  10  15
like image 58
jezrael Avatar answered May 18 '23 13:05

jezrael