New dataframe column based on a given condition
There are times when you would like to add a new DataFrame column based on some condition . Actually, there does not exist any Pandas library function to achieve this method directly.
Suppose you have a DataFrame like this:
You want to create a new column "Result" based on the following condition:
- A == B: 0
- A > B: 1
- A < B: -1
So, by applying above condition, DataFrame should be:
How yo can achieve above condition through Pandas DataFrame operation?
Lets create a DataFrame..
Operation on Single column
Suppose, you have a DataFrame like this:
You would like to add one more column for Result based on certain conditions.
- Marks <= 30 : Failed
- Marks >= 40 and <=49 : Passed
- Marks >= 50 and <=59 : Second Class
- Marks >= 60 and <=79 : First Class
- Marks >= 80 and <=100 : Top
How you can create a dataFrame column based on the above condition using DataFrame.loc .