Credics
Credics

Reputation: 67

Broadcast level of multiindex when using pandas DataFrame.dot

I want to do a matrix multiplication of a pandas dataframe and a series. The dataframe has the same index for both axes. The series has a multi index, whose second level matches the dataframe's index.

What is a good / the propper way to do a matrix multiplication while broadcasting the first level of the series' multi index?

import pandas as pd
import numpy as np

i1 = pd.Index(['a', 'b'], name='one')
i2 = pd.Index(['A', 'B'], name='two')
mi1 = pd.MultiIndex.from_product([i1, i2])
df = pd.DataFrame(np.array([[0, 1], [1, 0]]), index=i2, columns=i2)
s = pd.Series([1,2,3,4], index=mi1)

# I want to do something like
df1.dot(s1, level='two')

# Which would result in
one  two
a    A      2
     B      1
b    A      4
     B      3

Upvotes: 1

Views: 192

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150775

Try unstack s then dot:

([email protected](level=0)).unstack()

# or
# df.dot(s.unstack(level=0)).unstack()

Output:

one  two
a    A      2
     B      1
b    A      4
     B      3
dtype: int64

Upvotes: 1

Related Questions