gpt4 book ai didi

python - Pandas /Python : How to create new column based on values from other columns and apply extra condition to this new column

转载 作者:行者123 更新时间:2023-12-04 14:39:08 24 4
gpt4 key购买 nike

我有一个 Pandas 数据框,我想创建一个新列 BB 基于以下条件。

  • 创建新列 BB , 如果列 中的值TGR1 为 0,将 0 赋给 BB 否则,
  • 中的值TGR1 不为 0,查找与 中的值对应的列 ( '1','2','3' ) TGR1 将该列中的值( '1','2','3' )分配给新列 BB .

  • 我能够使用
    df.loc[df['TGR1'] == 0, 'BB'] = 0
    我也尝试使用 np.where 想出来,但我可以找出解决这个问题的正确方法。
    df['BB'] = np.where(df.TGR1 == 0,0, df.columns == test.TGR1.value )



    Dist Track EVENT_ID Date 1 2 3 TGR1 TGR2

    311m Cran 174331755 2020-10-19 34.00 5.18 19.10 1 0
    311m Cran 174331755 2020-10-19 34.00 5.18 19.10 2 1
    311m Cran 174331755 2020-10-19 34.00 5.18 19.10 0 2
    311m Cran 174331755 2020-10-19 34.00 5.18 19.10 3 1
    311m Cran 174331755 2020-10-19 34.00 5.18 19.10 2 2
    311m Cran 174331755 2020-10-19 34.00 5.18 19.10 1 2
    预期输出:
    Dist    Track    EVENT_ID      Date       1      2        3   TGR1 TGR2    BB     

    311m Cran 174331755 2020-10-19 34.00 5.18 19.10 1 0 34.00
    311m Cran 174331755 2020-10-19 34.00 5.18 19.10 2 1 5.18
    311m Cran 174331755 2020-10-19 34.00 5.18 19.10 0 2 0
    311m Cran 174331755 2020-10-19 34.00 5.18 19.10 3 1 19.10

    最佳答案

    一种方法是使用 numpy advanced indexing :

    import numpy as np
    # extract columns 1,2,3 into a numpy array with a zeros column stacked on the left
    vals = np.column_stack((np.zeros(len(df)), df[list('123')]))

    vals
    array([[ 0. , 34. , 5.18, 19.1 ],
    [ 0. , 34. , 5.18, 19.1 ],
    [ 0. , 34. , 5.18, 19.1 ],
    [ 0. , 34. , 5.18, 19.1 ],
    [ 0. , 34. , 5.18, 19.1 ],
    [ 0. , 34. , 5.18, 19.1 ]])

    # use TGR1 values as the column index to extract corresponding values
    df['BB'] = vals[np.arange(len(df)), df.TGR1.values]

    df
    Dist Track EVENT_ID Date 1 2 3 TGR1 TGR2 BB
    0 311m Cran 174331755 2020-10-19 34.0 5.18 19.1 1 0 34.00
    1 311m Cran 174331755 2020-10-19 34.0 5.18 19.1 2 1 5.18
    2 311m Cran 174331755 2020-10-19 34.0 5.18 19.1 0 2 0.00
    3 311m Cran 174331755 2020-10-19 34.0 5.18 19.1 3 1 19.10
    4 311m Cran 174331755 2020-10-19 34.0 5.18 19.1 2 2 5.18
    5 311m Cran 174331755 2020-10-19 34.0 5.18 19.1 1 2 34.00

    关于python - Pandas /Python : How to create new column based on values from other columns and apply extra condition to this new column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69330911/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com