【问题标题】:How do I turn categorical column values into different column names?如何将分类列值转换为不同的列名?
【发布时间】:2020-12-12 06:37:32
【问题描述】:

我不知道如何解决这个问题,因为我是 pandas 的初学者。

我有这个数据框:

  col1 col2
0    a    1 
1    a    2 
2    a    3 
3    b    4
4    b    5
5    b    6
6    c    7
7    c    8
8    c    9

我想把它变成这样的数据框或矩阵:

   cola colb  colc
0    1    4    7
1    2    5    8
2    3    6    9

我应该如何在 Python 中解决这个问题?

【问题讨论】:

    标签: python pandas dataframe matrix


    【解决方案1】:

    让我们 groupby col1 上的数据框并在 dict 理解中创建键值对:

    pd.DataFrame({k: [*g['col2']] for k, g in df.groupby('col1')})
    

    或者,您可以使用groupby + cumcount 创建一个顺序计数器来区分col1 中每个组的不同行,然后使用set_index + unstack 来重塑:

    df.set_index([df.groupby('col1').cumcount(), 'col1'])['col2'].unstack()
    

    pivot_tablegroupby + cumcount 的另一种方法:

    df.pivot_table(index=df.groupby('col1').cumcount(), columns='col1', values='col2')
    

    结果:

       a  b  c
    0  1  4  7
    1  2  5  8
    2  3  6  9
    

    【讨论】:

    • 附带说明:为了使用第一种方法,您必须在 col1 中的每组具有相同数量的行,但对于第二种和第三种方法,则不需要..
    猜你喜欢
    • 2023-02-24
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多