1

I have 4 columns in the dataframe and would like to change all the values in column 2 based on the below condition:

if pd.isnull(df['COL2']) or df['COL2'] == "SOME_NAME":
    if pd.isnull(df['COL3']) == False:
        df['COL2'] = df['COL3']
    else:
        df['COL2'] = "DEFAULT" 

so basically if col2 is empty or has some specific name replace it with col3 if col3 not empty else replace with default

I iterated over the df but the matching is not replacing all the values. I have some rows with col2 value still set to "SOME_NAME". Is there a simple way of doing this?

3 Answers 3

1

Use assignment with loc, to only change those rows that meet your condition.

i = df['COL2'].isnull() | df['COL2'].eq('SOME_NAME')
j = df.loc[i, 'COL3']

df.loc[i, 'COL2'] = j.where(j.notnull(), 'DEFAULT') 
Sign up to request clarification or add additional context in comments.

7 Comments

Is not better chain third condition?
@jezrael I don't know if they do the same thing, so I didn't chain it.
OK, I try test it.
It does replace most of it but there are still rows with "SOME_NAME" value
@hmaxx You might want to remove whitespaces, if any: df['COL2'].str.strip().eq('SOME_NAME')
|
0

I think you need numpy.where with chanined conditions by | for or and & for and:

mask = (df['COL2'].isnull() | (df['COL2'].str.strip() == "SOME_NAME")) & df['COL3'].notnull()

df['COL2'] = np.where(mask, df['COL3'], "DEFAULT")

Similar solution:

df['COL2'] = df['COL3'].where(mask, "DEFAULT")

Comments

0

The ternary operator was added in 2.5 i believe:

if (condition) else

sample dataframe:

df = pd.DataFrame({"COL2": ["first", None,"third","fourth", None], "COL3": ["first_","second_","third_","fourth_", None]})

so you can do something like this to replace value "third" or null :

df['COL2'] =df.apply(lambda row: row['COL3'] if ((not row['COL2'] or row['COL2'] == "third") and row['COL3']) else "DEFAULT", axis=1)

Output:

df
Out[21]: 
      COL2     COL3
0  DEFAULT   first_
1  second_  second_
2   third_   third_
3  DEFAULT  fourth_
4  DEFAULT     None

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.