2
$\begingroup$

I was trying to create a new column to a dataframe such that the new column should have the format as True/False based on some pattern.

My dataframe:

df = pd.DataFrame([[1,16],[21,3],[0.9,56]])
df.columns=['A','B']
df.index = ['1','2','3']
df

enter image description here

I want to create a new column such that if A > 2 and B < 30 will have value as True in a new column, otherwise should have value as False.

I tried to use np.where to get the new column but I am not sure how can I get values as True or False.

$\endgroup$
1
$\begingroup$

You could use np.where, but just using a series comparison should work as well:

df["col"] = (df["A"] > 2) & (df["B"] < 30)
$\endgroup$
0
$\begingroup$

Well, obviously the solution using a series comparison published by @Oxbowerce is the best option because it is not needed to import a big tool like Numpy for doing this simple task. However, if someone is asking for the solution that uses numpy.where, this could be as follow:

import numpy as np

df['New Column'] = np.where((df["A"] > 2) & (df["B"] < 30), True, False)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.