python - python中的列转换

标签 python pandas

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.extractffill 一起使用:

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/

相关文章:

python - 如何根据数据框中的列动态生成for循环?

python - 带提示数据集的 KNN

python - 按第二个元素对元组列表进行分组,取第一个元素的平均值

python - Python matplotlib 作为 cron 作业运行时出现 QxcbConnection 错误

python - 在 DataFrame 中多次拆分字符串

python - 默认的 Django 管理表单和 FormWizard

Python:如何使用带有很多参数的 os.spawnv?

python - 为每个问题生成一次随机值 Python

python - Plotly:如何在指定点添加垂直线?

python - 如何在 python 中向 groupby 中的聚合添加函数?