JChat
JChat

Reputation: 814

How to update a column value in dataframe if there is any missing value in specific column range?

I have a Pandas dataframe df with 80000 rows and 121 columns. I would like to update the last column values/change all values in last column to 999, in the conditions where any row in my data for columns 3 to 120 has a missing value (even one missing value).

For example, the expected result would be this

    Column 1 Column2 Column 3. Column 4......Column 120 Column 121
Row 1. 123    456.    244.      NA.            3434.       999 #Update Column 121 value to 999
Row 2  123.   NA.    444.      455            4545.       0   #Do not change existing value here
Row n. 123    343.    NA.     234            3434         999 #Update Column 121 value to 999

Any help in this regard is much appreciated. Cheers.

Upvotes: 1

Views: 395

Answers (3)

Hugo Salvador
Hugo Salvador

Reputation: 1104

Try this:

df.loc[df.iloc[:,3:120].isnull().sum(axis=1)>0, 'Column 121'] = 999

Upvotes: 0

r.ook
r.ook

Reputation: 13878

df.loc[df[df.columns[2:120]].T.isna().any(), 'Column 121'] = 999

As @QuangHoang mentioned, passing axis=1 to any() would eliminate the need for T:

df.loc[df[df.columns[2:120]].isna().any(axis=1), 'Column 121'] = 999

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150745

Use isna().any(1):

df['Column 121'] = np.where(df.iloc[:, 2:-1].isna().any(1), 999, df['Column 121'])

Upvotes: 1

Related Questions