pandas数据帧生成行

3

我有一个输入数据框:

import pandas as pd

# Define the input data
data = {
    'ID':  [500, 200, 300],
    'A': [3, 3, ''],
    'B': [3, 1, ''],
    'C': [2, '' ,''],
    'D': ['', 2, 1],
    'E': ['', '',2 ],
}

# Convert the input data to a Pandas DataFrame
df = pd.DataFrame(data)

输入表格

enter image description here

我需要将这个输入转换成下面的输出示例中所示:

enter image description here

如果您有任何想法,请分享。非常感谢!

1个回答

1
你可以使用每行的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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接