Cartesian product of a pandas dataframe with itself

后端 未结 3 1648
有刺的猬
有刺的猬 2020-12-10 19:59

Given a dataframe:

    id  value
0    1     a
1    2     b
2    3     c

I want to get a new dataframe that is basically the cartesian produ

3条回答
  •  伪装坚强ぢ
    2020-12-10 20:30

    I had this problem before , this is my solution ..

    import itertools
    import pandas as pd 
    c = list(itertools.product(DF.id.tolist(), DF.id.tolist()))
    Dic=dict(zip(DF.id, DF.value))
    df = pd.DataFrame(c , columns=['id', 'id_2'])
    df[['value','value_2']]=df.apply(lambda x:x.map(Dic))
    df.loc[df.id!=df.id_2,:]
    
    
    Out[125]: 
       id  id_2 value value_2
    1   1     2     a       b
    2   1     3     a       c
    3   2     1     b       a
    5   2     3     b       c
    6   3     1     c       a
    7   3     2     c       b
    

提交回复
热议问题