Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/jsf/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python np select if语句返回条件语句的值_Python_Python 3.x_Pandas_Numpy_If Statement - Fatal编程技术网

Python np select if语句返回条件语句的值

Python np select if语句返回条件语句的值,python,python-3.x,pandas,numpy,if-statement,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) t1=x['timestamp_1']

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

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


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

使用:

#转换为日期时间
x['timestamp_1']=pd.to_datetime(x['timestamp_1'])
x['timestamp_2']=pd.to_datetime(x['timestamp_2'])
t1=x['timestamp_1']

如果条件为真,则返回1,否则返回2。

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

df['new'] = [1 if x==True else 2 for x in list(df.timestamp_1 < df.timestamp_2)]
df['new']=[1如果x==True,则列表中x的值为2(df.timestamp_1
np.其中(cond,valueiftrue,valueiffalse)
pd.x[“”]
打字错误吗?是否应该是
x['column']
?当我尝试创建一个新列作为x['new']=np时。其中(t1,1,2)我得到如下错误值错误:值的长度与索引的长度不匹配等等抱歉-它工作了,但它为所有行提供了一个值2,即使它应该是1?我需要转换为datetime Previor吗@安基_91@Chris90:检查编辑的答案。:)希望对您有效。谢谢,但当我尝试此方法时,所有行的值都是2,即使应该是1?t1=x['time_1']x['time1']=pd.to_datetime(x['time1']将其转换为另一列
np.where(cond,valueiftrue,valueiffalse)
#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)
df['new'] = [1 if x==True else 2 for x in list(df.timestamp_1 < df.timestamp_2)]