Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.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 更改df中的整数的步骤_Python_Pandas_List Comprehension - Fatal编程技术网

Python 更改df中的整数的步骤

Python 更改df中的整数的步骤,python,pandas,list-comprehension,Python,Pandas,List Comprehension,我正试图在一个数据库中修改数据。使用下面的命令,其中X>=5,我想将相应的Y行更改为1。WhereX只需使用np即可。Where: import numpy as np df['Y'] = np.where(df['X'].ge(5),1,df['Y']) df['Y'] = np.where(df['X'].le(-5),0,df['Y']) 更好的是,对于多个条件,使用np。选择: conditions=[df['X'].ge(5),df['X'].le(-5)] choices=[1,

我正试图在一个数据库中修改数据。使用下面的命令,其中
X>=5
,我想将相应的
Y
行更改为
1
。Where
X只需使用
np即可。Where

import numpy as np
df['Y'] = np.where(df['X'].ge(5),1,df['Y'])
df['Y'] = np.where(df['X'].le(-5),0,df['Y'])

更好的是,对于多个条件,使用
np。选择

conditions=[df['X'].ge(5),df['X'].le(-5)]
choices=[1,0]
df['Y']=np.select(conditions,choices,default=df['Y'])

或者,如果您只想了解列表,请使用
zip

df['Y'] =[1 if x>=5 else(0 if x<=-5 else y)for x,y in zip(df['X'],df['Y'])] 

只需使用
np.where

import numpy as np
df['Y'] = np.where(df['X'].ge(5),1,df['Y'])
df['Y'] = np.where(df['X'].le(-5),0,df['Y'])

更好的是,对于多个条件,使用
np。选择

conditions=[df['X'].ge(5),df['X'].le(-5)]
choices=[1,0]
df['Y']=np.select(conditions,choices,default=df['Y'])

或者,如果您只想了解列表,请使用
zip

df['Y'] =[1 if x>=5 else(0 if x<=-5 else y)for x,y in zip(df['X'],df['Y'])] 

美好的因此,如果我包含一个包含
X2
的单独条件,那么使用
where
语句可能更有效?例如,
1如果x>5在x中,我认为最好使用
np。其中
,因为有很多条件的列表理解将不那么可读,您必须使zip更大,而使用
np。其中
您只需将条件与按位运算符连接起来即可@jonboy@MrNobody33
numpy。选择
将允许您在一个函数中考虑这两种情况call@PaulH-是的,那是真的,当答案被接受时,我正在考虑添加它,但我没有。但是既然您提到了它,并且OP正在考虑添加更多的条件,我将使用
np添加解决方案。选择更适合问题的
。感谢您合并
X2
,更好地使用
np。选择
;),请参见编辑后的答案@jonboyNice。因此,如果我包含一个包含
X2
的单独条件,那么使用
where
语句可能更有效?例如,
1如果x>5在x中,我认为最好使用
np。其中
,因为有很多条件的列表理解将不那么可读,您必须使zip更大,而使用
np。其中
您只需将条件与按位运算符连接起来即可@jonboy@MrNobody33
numpy。选择
将允许您在一个函数中考虑这两种情况call@PaulH-是的,那是真的,当答案被接受时,我正在考虑添加它,但我没有。但是既然您提到了它,并且OP正在考虑添加更多的条件,我将使用
np添加解决方案。选择更适合问题的
。感谢您合并
X2
,更好地使用
np。选择
;),见编辑后的答案@jonboy
original df
   X  X2  Y
0  -6  11  1
1 -10  10  0
2   6  15  1
3   9  12  0
4  -2   3  1
5  -5   2  0
6   5   6  1
7  -1  12  0
8   7  10  0
9  -6   9  0

df after np.where
    X  X2  Y
0  -6  11  0
1 -10  10  0
2   6  15  1
3   9  12  1
4  -2   3  1
5  -5   2  0
6   5   6  1
7  -1  12  0
8   7  10  1
9  -6   9  0