Check if multiple rows are filled and if not blank all values

Question:

I have the following dataframe:

ID  Name    Date    Code    Manager
1   Paulo   %   10  Jonh's Peter
2   Pedro   2001-01-20  20  
3   James       30  
4   Sofia   2001-01-20  40  -

I need a way to check if multiple columns (in this case Date, Code and Manager) are filled with any value. In the case there is any blank in any of those 3 columns, blank all the values in all 3 columns, returning this data:

ID  Name    Date    Code    Manager
1   Paulo   %   10  Jonh's Peter
2   Pedro           
3   James           
4   Sofia   2001-01-20  40  -

What is the best solution for this case?

Asked By: Paulo Cortez

||

Answers:

You can use pandas.isnull() with pandas.any(axis=1) then use pandas.loc for setting what value that you want.

col_chk = ['Date', 'Code', 'Manager']
m = df[col_chk].isnull().any(axis=1)
df.loc[m , col_chk] = '' # or pd.NA
print(df)

   ID   Name        Date  Code       Manager
0   1  Paulo           %  10.0  Jonh's Peter
1   2  Pedro                                
2   3  James                                
3   4  Sofia  2001-01-20  40.0             -
Answered By: I'mahdi

You can use pandas.DataFrame.loc to replace values in certain colums and based on a condition .

Considering that your dataframe is named df:

enter image description here

You can use this code to get the expected output :

df.loc[df[["Date", "Code", "Manager"]].isna().any(axis=1), ["Date", "Code", "Manager"]] = ''

>>> print(df)

enter image description here

Answered By: L'Artiste
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.