Pandas. I have a df with multiple columns. ColA has nan values. I want a new column with…
- User
Pandas. I have a df with multiple columns. ColA has nan values. I want a new column with 0 when nan otherwise 1
Assistant
Here is how you can create a new column that has 0 when ColA is NaN, and 1 otherwise:
import pandas as pd import numpy as np df = pd.DataFrame({'ColA': [1, np.nan, 3, np.nan]}) df['NewCol'] = np.where(df['ColA'].isnull(), 0, 1) print(df)This uses np.where() to check if ColA is null/NaN, and assign 0 if so, else assign 1.
The output will be:
ColA NewCol 0 1.0 1 1 NaN 0 2 3.0 1 3 NaN 0
So this creates a new binary column NewCol that indicates whether ColA was NaN or not.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.