Cartesian product from two Series, different lengths and indexes

后端 未结 2 1556
夕颜
夕颜 2021-01-21 06:08

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],         


        
相关标签:
2条回答
  • 2021-01-21 06:22

    You can use NumPy broadcasting to multiply the values of one series by the transposed values of the other.

    res = pd.DataFrame(ser1.values * ser2.values[:, None],
                       index=ser2.index, columns=ser1.index)
    
    print(res)
    
       1   2   3
    a  1   2   3
    b  2   4   6
    c  3   6   9
    d  4   8  12
    e  5  10  15
    
    0 讨论(0)
  • 2021-01-21 06:34

    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
    
    0 讨论(0)
提交回复
热议问题