3

I have a pd Dataframe and some values are nan.

What I would like to do is assign nan values to all the elements of a row (excluding the element of the first column) if that row has one nan value.

For example, given the following dataframe:

Code   1996   1997   1998
GBA    100    nan     5
JOY    120    10      30
WII    300    nan     nan

the desired output is:

Code   1996   1997   1998
GBA    nan    nan     nan
JOY    120    10      30
WII    nan    nan     nan

1 Answer 1

3

You can first get a boolean series that says whether a row has any NaNs in it starting from first column. Then you can use boolean indexing and set those rows' columns starting from first to NaN:

has_nan = df.loc[:, "1996":].isna().any(axis=1)

df.loc[has_nan, "1996":] = np.nan

to get

>>> df

  Code   1996  1997  1998
0  GBA    NaN   NaN   NaN
1  JOY  120.0  10.0  30.0
2  WII    NaN   NaN   NaN

has_nan is

0     True
1    False
2     True
dtype: bool

i.e., first and last rows are NaNed.

Sign up to request clarification or add additional context in comments.

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.