Cody Smith
Cody Smith

Reputation: 123

Creating a New DataFrame Column by Using a Comparison Operator

I have a DataFrame that looks like something similar to this:

    0
0   3
1  11
2   7
3  15

And I want to add a column using two comparison operators. Something like this:

df[1] = np.where(df[1]<= 10,1 & df[1]>10,0)

I want my return to look like this:

    0   1
0   3   1
1  11   0
2   7   1
3  15   0

But, I get this error message:

TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

Any help would be appreciated!

Upvotes: 0

Views: 100

Answers (1)

Allen Qin
Allen Qin

Reputation: 19947

Setup

df = pd.DataFrame({'0': {0: 3, 1: 11, 2: 7, 3: 15}})
Out[1292]: 
    0
0   3
1  11
2   7
3  15

Solution

#compare df['0'] to 10 and convert the results to int and assign it to df['1']
df['1'] = (df['0']<10).astype(int)

df
Out[1287]: 
    0  1
0   3  1
1  11  0
2   7  1
3  15  0

Upvotes: 1

Related Questions