gpt4 book ai didi

python - 根据优先级在 Pandas 数据框中创建二进制列

转载 作者:太空宇宙 更新时间:2023-11-03 15:34:28 24 4
gpt4 key购买 nike

我有一个看起来像这样的 pandas 数据框:

Item    Status
123 B
123 BW
123 W
123 NF
456 W
456 BW
789 W
789 NF
000 NF

我需要创建一个新列 Value ,它是 1 或 0,具体取决于 ItemStatus 列中的值.值 1 的分配按以下顺序排列优先级:BBWWNF。因此,使用上面的示例数据框,结果应该是:

Item    Status    Value
123 B 1
123 BW 0
123 W 0
123 NF 0
456 W 0
456 BW 1
789 W 1
789 NF 0
000 NF 1

使用 Python 3.7。

最佳答案

将您的原始数据框作为输入 df 数据框,以下代码将产生您想要的输出:

#dictionary assigning order of priority to status values
priority_map = {'B':1,'BW':2,'W':3,'NF':4}

#new temporary column that converts Status values to order of priority values
df['rank'] = df['Status'].map(priority_map)

#create dictionary with Item as key and lowest rank value per Item as value
lowest_val_dict = df.groupby('Item')['rank'].min().to_dict()

#new column that assigns the same Value to all rows per Item
df['Value'] = df['Item'].map(lowest_val_dict)

#replace Values where rank is different with 0's
df['Value'] = np.where(df['Value'] == df['rank'],1,0)

#delete rank column
del df['rank']

关于python - 根据优先级在 Pandas 数据框中创建二进制列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55680165/

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