用熊猫生成矩阵

时间:2017-12-19 00:29:12

标签: pandas matrix count

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

按ID分组

低:中上:结束

第1天:计算if(如果级别有Mid和End,如果day == 1)

第2天:计算if(如果级别有Mid和End,如果day == 2)

...

开始:从中到新

第1天:计算if(如果级别有Mid和New,如果day == 1)

第2天:计算if(如果级别有Mid和New,如果day == 2)

...

df = pd.DataFrame({' Id':[111,111,222,333,333,444,555,555,555,666,666],'等级':[' End'' Mid' '结束''结束''中间''新''结束','新的','中'新''中'日':'' ; 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

Mid New 0 1 0 1

新结束0 0 1 0

New Mid 0 0 0 1

谢谢!谢谢!

1 个答案:

答案 0 :(得分:1)

从您的数据框开始

 # 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)]