Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

python - Replace on column value dependgin on other columns and conditions in pandas

Hello I have a dataframe such as

COL1 COL2 COL3 COL4 COL5
G1   NaN  NaN  NaN  A
G1   NaN  Lop  NaN  A 
G2   NaN  NaN  NaN  B 
G3   Sil  NaN  SLO  A
G4   NaN  NaN  NaN  C
G4   LIJ  KYI  NaN  B

Then the idea it to replace COL2 values by OK if COL2,COL3,COL4 == "NaN" & COL5 is in list("A","B")

I should get

COL1 COL2 COL3 COL4 COL5
G1   OK   NaN  NaN  A
G1   NaN  Lop  NaN  A 
G2   OK  NaN  NaN  B 
G3   Sil  NaN  SLO  A
G4   NaN  NaN  NaN  C
G4   LIJ  KYI  NaN  B

So far I tried:

tab['COL2'][(tab['COL2'].isna()) & (tab['COL3'].isna()) & (tab['COL4'].isna()) & tab['COL5'].str.contains("A|B"))] = "OK"
question from:https://stackoverflow.com/questions/66064286/replace-on-column-value-dependgin-on-other-columns-and-conditions-in-pandas

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try with all + isna

df.loc[df.COL5.isin(['A','B']) & df[['COL2','COL3','COL4']].isna().all(1),'COL2']='OK'
df
Out[22]: 
   COL1 COL2 COL3 COL4 COL5
0   G1   OK  NaN  NaN    A
1   G1  NaN  Lop  NaN    A
2   G2   OK  NaN  NaN    B
3   G3  Sil  NaN  SLO    A
4   G4  NaN  NaN  NaN    C
5   G4  LIJ  KYI  NaN    B

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...