Search code examples
pythonobjectlambdaisnull

Pandas-Lambda for different objects in same column


For this dataframe:

import pandas as pd
df=pd.DataFrame([[2],['do-g'],['ra-t'],['ca-t'],[5]], columns=['A'])
print(df)

To values in Column 'A' are treated as 'int' values. How do I add a new column (derived from the 'A' column) that has the '-' removed from the words but leaves the numbers/ integers as they are?

My attempted solution:

df['new_column']=df.A.apply(lambda x: x.replace('-') if x.isnull() else x)

Solution

  • You could ignore the non string values in your lambda.

    >>> df['new_column'] = df.A.apply(lambda x: x.replace('-', '') if isinstance(x,str) else x)
    >>> df
          A new_column
    0     2          2
    1  do-g        dog
    2  ra-t        rat
    3  ca-t        cat
    4     5          5