数据透视表将行复制到新列中

数据透视表将行复制到新列中,第1张

数据透视表将行复制到新列中

使用

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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/zaji/5663653.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存