2017-05-05 35 views
0

创建一个新的数据框栏我有一个数据帧,看起来像类似于这样:通过使用比较操作

0 
0 3 
1 11 
2 7 
3 15 

我要添加使用两个比较操作的列。事情是这样的:

df[1] = np.where(df[1]<= 10,1 & df[1]>10,0) 

我希望我回到这个样子:

0 1 
0 3 1 
1 11 0 
2 7 1 
3 15 0 

但是,我得到这个错误信息:

TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool] 

任何帮助,将不胜感激!

+3

如若'10,1'和'10,0'会有'10.1'和​​'10.0'呢?因为它看起来好像在'where'中评估三件事物,其中之一是'1&df [1]> 10',这可能是导致类型错误的原因。 – bouteillebleu

回答

0

设置

df = pd.DataFrame({'0': {0: 3, 1: 11, 2: 7, 3: 15}}) 
Out[1292]: 
    0 
0 3 
1 11 
2 7 
3 15 

解决方案

#compare df['0'] to 10 and convert the results to int and assign it to df['1'] 
df['1'] = (df['0']<10).astype(int) 

df 
Out[1287]: 
    0 1 
0 3 1 
1 11 0 
2 7 1 
3 15 0 
+0

太棒了。谢谢您的帮助。对此,我真的非常感激! –

+0

不用担心。如果它有用,请接受它作为答案。 – Allen