np选择if语句以返回条件语句的值

时间:2019-01-08 06:08:26

标签: python python-3.x pandas numpy if-statement

我想创建一个新列,如果以下条件为true,则返回值1;如果为false,则返回2,并且不确定为什么以下条件不起作用?

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


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

3 个答案:

答案 0 :(得分:1)

使用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)

其功能类似于:

np.where(cond,valueiftrue,valueiffalse)

答案 1 :(得分:0)

使用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)

如果条件为true,它将返回1,否则将返回2。

答案 2 :(得分:0)

您可以在转换时间戳(pd.to_datetime)后之后使用直观的列表理解方法,如下所示:

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