【问题标题】:Create new column based on values from another one根据另一列的值创建新列
【发布时间】:2021-12-02 19:32:15
【问题描述】:

我的 df 如下所示:

column1  column2 
x        X22
x        X26        
x        X287
y        X26
y        X22
y        X287
y        X26
z        X27
c        X29
c        X22

我想创建一个新列,输出应该是这样的:

column1  column2 column3
x        X22      1
x        X26      2 
x        X287     3
y        X26      1
y        X22      2
y        X287     3
y        X26      4
z        X27      1
c        X29      1
c        X22      2

如您所见,我需要一个基于 column1 的值从 1 到 x 的列。因此,如果在 column1 中我们有值“x”,我想创建一个值从 1 到 3 的列 3。我不能使用 groupby,因为我必须保留我的 column2。你有什么想法吗?

问候 托马斯

【问题讨论】:

    标签: python pandas for-loop append multiple-columns


    【解决方案1】:

    你可以使用groupby+cumcount:

    df['column3'] = df.groupby('column1').cumcount().add(1)
    

    输出:

      column1 column2  column3
    0       x     X22        1
    1       x     X26        2
    2       x    X287        3
    3       y     X26        1
    4       y     X22        2
    5       y    X287        3
    6       y     X26        4
    7       z     X27        1
    8       c     X29        1
    9       c     X22        2
    

    【讨论】:

    • 你很快 :D 谢谢,它有效
    猜你喜欢
    • 2020-04-16
    • 2022-08-12
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2020-04-28
    • 2018-08-15
    相关资源
    最近更新 更多