MikeRand
MikeRand

Reputation: 4838

pandas - how do I produce cartesian product of both indices and data?

>>> y = pandas.DataFrame.from_dict({'{}': {'A': 0.2, 'B': 0.3, 'C': 0.4, 'D': 0.1}})

>>> z = pandas.DataFrame.from_dict({'{}': {'L': 0.25, 'M': 0.35, 'N': 0.10, 'O': 0.30}})

>>> y
    {}
A  0.2
B  0.3
C  0.4
D  0.1

>>> z
     {}
L  0.25
M  0.35
N  0.10
O  0.30

>>> want(y, z)
       {}
A L 0.050
A M 0.070
A N 0.020
A O 0.060
B L 0.075
B M 0.105
B N 0.030
B O 0.090
C L 0.100
C M 0.140
C N 0.040
C O 0.120
D L 0.025
D M 0.035
D N 0.010
D O 0.030

How do I implement want?

I've read through and tried all merge combinations.

Upvotes: 4

Views: 1355

Answers (1)

IanS
IanS

Reputation: 16271

One simple way would be to use pandas.MultiIndex.from_product:

index = pandas.MultiIndex.from_product([y.index, z.index])
s = pandas.Series([y.loc[i[0], '{}'] * z.loc[i[1], '{}'] for i in index], index=index)

Result:

A  L    0.050
   M    0.070
   N    0.020
   O    0.060
B  L    0.075
   M    0.105
   N    0.030
   O    0.090
C  L    0.100
   M    0.140
   N    0.040
   O    0.120
D  L    0.025
   M    0.035
   N    0.010
   O    0.030
dtype: float64

Upvotes: 4

Related Questions