Home > Software design >  Creating a new column by applying a arithmetic function in an existing column
Creating a new column by applying a arithmetic function in an existing column

Time:11-04

I tried to create a column from an existing column by subtracting it's values by a constant value. The issue is the existing column consists of both integer and string values , and I only want to apply subtraction to the integer values . So I want the subtracted result of the integer values and NaN for the string values in the new column . The dtype of the column is object . Please do help , if anyone knows a solution for this . Thanks in advance. I have given a small example to explain my query .

df1 = pd.DataFrame({"Fruits":['apple','banana','mango','strawberry'],
                "P":['100','100VT','60VT','70'],
                "C":[1,2,3,4],
                "S":['A','A','A','A']})

The input dataframe

The below picture is the output dataframe that I need , where P_new column = P-50. Only the integer values of the P column is subtracted by 50 , the row corresponding to the string values is an empty cell .

The output dataframe with the new column P_new

CodePudding user response:

User pd.to_numeric with errors='coerce':

df1['P_new'] = pd.to_numeric(df1['P'], errors='coerce') - 50

Output:

       Fruits      P  C  S  P_new
0       apple    100  1  A   50.0
1      banana  100VT  2  A    NaN
2       mango   60VT  3  A    NaN
3  strawberry     70  4  A   20.0
  • Related