代码之家  ›  专栏  ›  技术社区  ›  TylerNG

使用pandas生成矩阵

  •  0
  • TylerNG  · 技术社区  · 8 年前

    我想使用pandas为数据df生成一个矩阵,逻辑如下:

    按id分组

    低:中上:结束

    对于第1天:计算if(如果级别有中间和结尾,并且如果日期==1)

    对于第2天:计算if(如果级别有中间和结尾,并且如果日期==2)

    .

    开始:中到新

    对于第1天:计算if(如果级别有Mid和New,并且如果日期==1)

    对于第2天:计算if(如果级别有Mid和New,并且如果日期==2)

    .

    df=pd。数据帧({'Id':[111111 22233334445555555566666],'Level':['End','Mid','End','Mid','New','End','New','Mid','New','Mid','day':['',3','','',2,3',3,4',2]})

    Id |级别|天

    111 |结束|

    111 |中| 3

    222 |结束|

    333 |结束|

    333 |中| 2

    444 |新| 3

    555 |结束|

    555 |新| 3

    555 |中| 4

    666 |新|

    666 |中| 2

    矩阵如下所示:

    低顶第1天第2天第3天第4天

    中端0 1 1 0

    中新0 1 0 1

    新结束0 0 1 0

    新建Mid 0 0 1

    非常感谢。非常感谢。

    1 回复  |  直到 8 年前
        1
  •  1
  •   00__00__00    8 年前

    从数据帧开始

     # all the combination of Levels
    level_combos=[c for c in itertools.combinations(df['Level'].unique().tolist(), 2)]
     # create output and fill with zeros
    df_output=pd.DataFrame(0,index=level_combos,columns=range(4))
    

    可能效率不高,但应该可以

    for g in df.groupby(['Id']): # group by ID
        # combination of levels for this ID
        level_combos_this_id=[c for c in itertools.combinations(g[1]['Level'].unique().tolist(), 2)]
    
    
       # set to 1 the days present
        df_output.loc[level_combos_this_id,pd.to_numeric(g[1]['day']).dropna(inplace=True).values]=1
    

    最后重命名列以获得所需的输出

    df_output.columns=['day'+str(i+1) for i in range(4)]