max
数来repeat
行,然后与groupby.cumcount
进行比较以映射1
/''
。tmp = df.set_index('ID').apply(pd.to_numeric, errors='coerce')
out = (
tmp.loc[tmp.index.repeat(tmp.max(axis=1))]
.pipe(lambda d: d.gt(d.groupby(level='ID').cumcount(), axis=0))
.replace({True: 1, False: ''})
.reset_index()
)
注意:如果您使用NaN
代替空字符串,可以简化代码。
输出:
ID A B C D E
0 500 1 1 1
1 500 1 1 1
2 500 1 1
3 200 1 1 1
4 200 1 1
5 200 1
6 300 1 1
7 300 1