Chris90
Chris90

Reputation: 1998

np select if statement to return a value for a conditional statement

I want to create a new column that returns a value of 1 if the below condition is true and 2 if false and am not sure why the below isn't working?

t1 = x['timestamp_1'] < x['timestamp_2']


x['new'] = np.select([t1], [1], default=2)

Upvotes: 0

Views: 1362

Answers (3)

Neo
Neo

Reputation: 627

You can use the intuitive list comprehension after you convert your timestamps (pd.to_datetime), like this:

df['new'] = [1 if x==True else 2 for x in list(df.timestamp_1 < df.timestamp_2)]

Upvotes: 0

Mohit Motwani
Mohit Motwani

Reputation: 4792

Use np.where:

#Convert to datetime
x['timestamp_1'] = pd.to_datetime(x['timestamp_1'])
x['timestamp_2'] = pd.to_datetime(x['timestamp_2'])
t1 = x['timestamp_1'] < x['timestamp_2']

x['new']  = np.where(t1, 1, 2)

If the condition is true it will return 1 else it will return 2.

Upvotes: 0

anky
anky

Reputation: 75080

use numpy where

#convert both columns to pd.to_datetime

x[['timestamp_1','timestamp_2']] = x[['timestamp_1','timestamp_2']].apply(pd.to_datetime,errors='coerce')

t1 = x['timestamp_1'] < x['timestamp_2']
x['new'] = np.where(t1,1,2)

which functions like:

np.where(cond,valueiftrue,valueiffalse)

Upvotes: 1

Related Questions