使用
cumcount了数组,创建
MultiIndex通过
set_index与
unstack列和最后一个扁平化的值:
g = df.groupby(["ID","Agent", "OV"]).cumcount().add(1)df = df.set_index(["ID","Agent","OV", g]).unstack(fill_value=0).sort_index(axis=1, level=1)df.columns = ["{}{}".format(a, b) for a, b in df.columns]df = df.reset_index()print (df) ID Agent OV Zone1 Value1 PTC1 Zone2 Value2 PTC2 Zone3 Value3 PTC30 1 10.0 26.0 M1 10 100 0 0 0 0 0 01 2 26.5 8.0 M2 50 95 M1 6 5 0 0 02 3 4.5 6.0 M3 4 40 M4 6 60 0 0 03 4 1.2 0.8 M1 8 100 0 0 0 0 0 04 5 2.0 0.4 M1 6 10 M2 41 86 M4 2 4
如果只想替换为
0数字列:
g = df.groupby(["ID","Agent"]).cumcount().add(1)df = df.set_index(["ID","Agent","OV", g]).unstack().sort_index(axis=1, level=1)idx = pd.IndexSlicedf.loc[:, idx[['Value','PTC']]] = df.loc[:, idx[['Value','PTC']]].fillna(0).astype(int)df.columns = ["{}{}".format(a, b) for a, b in df.columns]df = df.fillna('').reset_index()print (df) ID Agent OV Zone1 Value1 PTC1 Zone2 Value2 PTC2 Zone3 Value3 PTC30 1 10.0 26.0 M1 10 100 0 0 0 01 2 26.5 8.0 M2 50 95 M1 6 5 0 02 3 4.5 6.0 M3 4 40 M4 6 60 0 03 4 1.2 0.8 M1 8 100 0 0 0 04 5 2.0 0.4 M1 6 10 M2 41 86 M4 2 4
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)