df['A'] after running this code?import pandas as pd df = pd.DataFrame({'A': ['1', '2', 'three', '4']}) df['A'] = pd.to_numeric(df['A'], errors='coerce') print(df['A'])
errors='coerce' handles non-numeric values.The pd.to_numeric function converts values to numbers. When errors='coerce' is set, any value that cannot be converted becomes NaN. So 'three' becomes NaN, and the column dtype becomes float64 because NaN is a float.
'B' have after conversion?import pandas as pd df = pd.DataFrame({'B': ['10', '20', '30', '20', 'ten']}) df['B'] = pd.to_numeric(df['B'], errors='coerce') unique_count = df['B'].nunique(dropna=True) print(unique_count)
nunique(dropna=True) excludes NaN values.The values after conversion are 10.0, 20.0, 30.0, 20.0, and NaN (from 'ten'). The unique non-NaN values are 10.0, 20.0, and 30.0, so the count is 3.
import pandas as pd df = pd.DataFrame({'dates': ['2023-01-01', 'not_a_date', '2023-03-01']}) df['dates'] = pd.to_datetime(df['dates'], format='%Y-%m-%d')
pd.to_datetime behaves when a string does not match the format and no errors parameter is given.The format parameter enforces strict parsing. The string 'not_a_date' does not match the format '%Y-%m-%d', so pd.to_datetime raises a ValueError unless errors='coerce' or errors='ignore' is set.
import pandas as pd df = pd.DataFrame({'vals': ['5', '10', 'abc', '20']})
Option D converts invalid strings to NaN with errors='coerce', then replaces NaN with 0, and finally converts the column to integers.
Option D does not convert invalid strings and fillna(0) will not work properly. Option D raises an error because 'abc' cannot be cast to int. Option D raises an error on invalid strings.
NaN is a special floating-point value. Integer types in pandas (and numpy) cannot represent NaN. So when a column has integers and NaN, pandas upcasts the column to float to accommodate NaN.