Issue
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 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 .
Solution
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
Answered By - Quang Hoang
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.