我试图打破这种循环心态:
df = pd.DataFrame(data = np.arange(1,11), columns=['x'])这给了我一列10项,从1到10。我想要创建一个新的列y,如果x小于5时,y是0,否则等于x。以下是我所做的:
def f(x):
if x < 5:
return 0
else:
return x
col = df['x']
df['y'] = col.apply(f)有更好的方法吗?
发布于 2015-03-24 21:27:06
使用where有条件地赋值为true,如果为false则返回不同的值:
In [57]:
df['y'] = df['x'].where(df['x']>5, 0)
df
Out[57]:
x y
0 1 0
1 2 0
2 3 0
3 4 0
4 5 0
5 6 6
6 7 7
7 8 8
8 9 9
9 10 10https://stackoverflow.com/questions/29243167
复制相似问题