0

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)
2
  • np.where(cond,valueiftrue,valueiffalse) Commented Jan 8, 2019 at 6:10
  • Is pd.x[''] a typo? should it be x['column']? Commented Jan 8, 2019 at 6:15

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

when I try to create a new column as x['new'] = np.where(t1,1,2) I get error as below ValueError: Length of values does not match length of index
wait sorry - it worked but it is giving a value of 2 for all rows, even when it should be 1? do I need to convert to datetime prior? @anky_91
@Chris90 : check edited answer. :) Hope that works for you.
0

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.

2 Comments

Thanks, but when I try this it gives a value of 2 for all rows even when should be 1? t1 = x['time_1'] < x['time_2'] x['new'] = np.where(t1, 1, 2)
Are your columns time1 and time2 converted to datetime type? If they are strings, it will work as you said. Convert them using x['time1'] = pd.to_datetime(x['time1'] and similary for the other column
0

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)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.