gpt4 book ai didi

python - 如何在Pandas数据框中的其他列中填充基于新列的值

转载 作者:行者123 更新时间:2023-12-03 22:37:46 25 4
gpt4 key购买 nike

我的数据框df如下所示。

  df
DATA ELEMENT PORT LOCATION P_RISK S_RISK W_RISK Total_Risk
Event 1000 SGSIN 0 0 0 0
Event 2000 MYKUL 0 1 0 1
Event 3000 PARIS 0 0 1 1
Event 4000 LYON 1 0 0 1
Event 1000 USNYK 0 0 0 0
Event 2000 INCOK 0 0 1 1
Event 3000 MUMBAI 0 0 0 0
Event 4000 LAHORE 1 0 0 1
Event 2000 INCOK 0 0 0 0
Event 3000 PARIS 0 0 0 0


健康)状况

*如果 Data Element为1000或2000,并且 Total Risk为1,则使用带有“风险名称+端口”的新列 comment

*如果 Data Element为3000或4000并且 Total Risk为1,则用With comment填充新列 Risk Name + LOCATION

*如果 Total Risk为0,则填充无风险标识

预期产量

df
DATA ELEMENT PORT LOCATION P_RISK S_RISK W_RISK Total_Risk Comment
Event 1000 SGSIN 0 0 0 0 No Risk Indentified
Event 2000 MYKUL 0 1 0 1 S_RISK predicted at MYKUL
Event 3000 PARIS 0 0 1 1 W_RISK predicted at PARIS
Event 4000 LYON 1 0 0 1 P_RISK predicted at LYON
Event 1000 USNYK 0 0 0 0 No Risk Indentified
Event 2000 INCOK 0 0 1 1 W_RISK predicted at INCOK
Event 3000 MUMBAI 0 0 0 0 No Risk Indentified
Event 4000 LAHORE 1 0 0 1 P_RISK predicted at LAHORE
Event 2000 INCOK 0 0 0 0 No Risk Indentified
Event 3000 PARIS 0 0 0 0 No Risk Indentified


如何才能做到这一点?

最佳答案

我在dot中使用np.where

s2=df.filter(like='_RISK')
s2=s2.dot(s2.columns)
df['new']=np.where(s2=='' ,'No Risk Indentified',s2 + ' predict at ' +df.PORT.mask(df.PORT=='',df.LOCATION))
df
Out[35]:
DATA ELEMENT PORT ... W_RISK Total_Risk new
0 Event 1000 SGSIN ... 0 0 No Risk Indentified
1 Event 2000 MYKUL ... 0 1 S_RISKpredict atMYKUL
2 Event 3000 ... 1 1 W_RISKpredict atPARIS
3 Event 4000 ... 0 1 P_RISKpredict atLYON
4 Event 1000 USNYK ... 0 0 No Risk Indentified
5 Event 2000 INCOK ... 1 1 W_RISKpredict atINCOK
6 Event 3000 ... 0 0 No Risk Indentified
7 Event 4000 ... 0 1 P_RISKpredict atLAHORE
8 Event 2000 INCOK ... 0 0 No Risk Indentified
9 Event 3000 ... 0 0 No Risk Indentified
[10 rows x 9 columns]


方法二

s2=df.filter(like='_RISK').ne(0).stack()                                                                             
s2=s2[s2].reset_index(level=1)
df['new']=(s2['level_1'] + ' predict at ' +df.PORT.mask(df.PORT=='',df.LOCATION)).fillna('No Risk Indentified')

关于python - 如何在Pandas数据框中的其他列中填充基于新列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58965746/

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