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
codeimport pandas as pd # Create a sample DataFrame with a column 'ColA' containing NaN values df = pd.DataFrame({'ColA': [1, 2, np.nan, 4, 5, np.nan, 7]}) # Create a new column 'ColB' with 0 when 'ColA' is NaN, otherwise 1 df['ColB'] = np.where(df['ColA'].isna(), 0, 1) # Display the resulting DataFrame print(df)Output:
codeColA ColB 0 1.0 1.0 1 2.0 1.0 2 NaN 0.0 3 4.0 1.0 4 5.0 1.0 5 NaN 0.0 6 7.0 1.0
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.