O 有此表,其中 type
列显示 3 个级别的信息。我想将第二层和第三层转换为单独的列。
number type
10 type 1
10 bottom
10 up
10 1
10 2
10 3
20 type 2
20 bottom
20 up
20 1
20 2
20 3
预期结果如下:
number type description detail
10 type 1 bottom bottom
10 type 1 up 1
10 type 1 up 2
10 type 1 up 3
20 type 2 bottom bottom
20 type 2 up 1
20 type 2 up 2
20 type 2 up 3
有什么办法可以用 python 实现吗?
提前致谢
最佳答案
您可以将 pandas str.extract
与 ffill
一起使用:
df['type_new'] = df['type'].str.extract(('(type.*)')).ffill()
df['detail'] = df['type'].str.extract('(bottom|[0-9])').ffill()
df['description'] = df['type'].str.extract('(bottom|up)').ffill()
最后使用掩码仅获取所需的行,并根据需要重命名列:
df = df[df['type'].isin(df['detail'].values)].reset_index(drop=True)[['number', 'type_new', 'description', 'detail']].rename(columns={'type_new':'type'})
输出:
number type description detail
0 10 type 1 bottom bottom
1 10 type 1 up 1
2 10 type 1 up 2
3 10 type 1 up 3
4 20 type 2 bottom bottom
5 20 type 2 up 1
6 20 type 2 up 2
7 20 type 2 up 3
关于python - python中的列转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67567077/