Search code examples
pythonpandasmethod-chaining

How do I replace a string-value in a specific column using method chaining?


I have a pandas data frame, where some string values are "NA". I want to replace these values in a specific column (i.e. the 'strCol' in the example below) using method chaining.

How do I do this? (I googled quite a bit without success even though this should be easy?! ...)

Here is a minimal example:

import pandas as pd

df = pd.DataFrame({'A':[1,2,3,4],
                   'B':['val1','val2','NA','val3']})
df = (
    df
    .rename(columns={'A':'intCol', 'B':'strCol'})  # method chain example operation 1
    .astype({'intCol':float})  # method chain example operation 2
    # .where(df['strCol']=='NA', pd.NA) # how to replace the sting 'NA' here? this does not work ...
    )
df

Solution

  • You can try replace instead of where:

    df.replace({'strCol':{'NA':pd.NA}})