1

I have a data frame like below:

s1 AA AG AG GG AA
s2 DI DD GG GG GG
S3 TT CC TC TT TC
S3 AA DI AA AA AA
S3 CC CC DD CC CC

and I want to replace all other strings to II in the row, if there is DI or DD in the row. so final dataframe should be like this.

s1 AA AG AG GG AA
s2 DI DD II II II
S3 TT CC TC TT TC
S3 II DI II II II
S4 II II DD II II

Any suggestions is appreciated. Thank you in advance

2 Answers 2

2

Check both values by DataFrame.isin and then replace only rows with at least one True with DataFrame.where:

m = df.isin(['DI','DD'])
m1 = m.any(1)
df[m1] = df[m1].where(m, 'II')

Or use numpy broadcasting for chain both masks:

m = df.isin(['DI','DD'])

df = df.where(m.values | ~m.any(1).values[:, None], 'II')

print (df)
    0   1   2   3   4   5
0  s1  AA  AG  AG  GG  AA
1  II  DI  DD  II  II  II
2  S3  TT  CC  TC  TT  TC
3  II  II  DI  II  II  II
4  II  II  II  DD  II  II

EDIT:

Working with - is possible by chained mask by | for bitwise OR:

print (df)
    0   1   2   3   4   5
0  s1  AA  AG  AG  GG   -
1  s2  DI  DD  GG  GG   -
2  S3  TT  CC  TC  TT  TC
3  S3  AA  DI  AA  AA  AA
4  S3  CC  CC  DD  CC  CC

m = df.isin(['DI','DD'])
m1 = m.any(1)
df[m1] = df[m1].where(m | df.eq('-'), 'II')
print (df)
    0   1   2   3   4   5
0  s1  AA  AG  AG  GG   -
1  II  DI  DD  II  II   -
2  S3  TT  CC  TC  TT  TC
3  II  II  DI  II  II  II
4  II  II  II  DD  II  II
Sign up to request clarification or add additional context in comments.

8 Comments

What if there is "--" in one of the columns of the row which has DD or DI, " and we don't want to replace it with II?
@jamo - Do you think add this value to m = df.isin(['DI','DD', '-']) ?
@jamo - Can you test m = df.replace('-', np.nan).isin(['DI','DD']) ?
@jezreal - it didn't work. how can specify AA/CC/GG/TT instead of "any" for m?
@jezreal - Awesome, perfect.Thank you
|
1
m = df.isin(['DI','DD']).sum(axis=1).astype(bool)

df.loc[m,:] = df.loc[m,:].applymap(lambda x: x if x in ["DI","DD"] else "II")
print(df)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.