2016-12-09 6 views
1

値Iはdf他の列の上にベクトル化の方法のコンディショニングにデータフレームをパンダに列を追加する

>>> df 
      a b c 
0   1 1 0    
1   1 -1 1      
2   1 0 0 

パンダのデータフレームを持っている今、私は列abに新しい列DF [「E」]コンディショニングを追加します。私はベクトル化された方法で新しい列を作成したいと思います。

df["e"] = [-1 if (df['a'] == 1 and df['b'] == 1) else 1] 

べき出力:

>>> df 
       a b c e 
    0   1 1 0 -1   
    1   1 -1 1 1     
    2   1 0 0 1 

しかし、私は次のエラーを取得しています:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/Users/hmishfaq/anaconda/lib/python2.7/site-packages/pandas/core/generic.py", line 917, in __nonzero__ 
    .format(self.__class__.__name__)) 
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

私は何を今、私は次のようにやっているために

間違っているとここにベクター化の正しい方法は何ですか?

PS:私が使用する必要がある元のデータフレームは本当に大きいので、for-loopはこれを永遠に実行します。

答えて

3

あなたは非常に高速numpy.whereを使用することができます。

df['e'] = np.where((df['a'] == 1) & (df['b'] == 1), -1, 1) 
print (df) 
    a b c e 
0 1 1 0 -1 
1 1 -1 1 1 
2 1 0 0 1 
関連する問題