2016-04-13 28 views
3

私はパンダのデータフレームのポイントを2つの条件に依存させようとしています。例:pandas np.whereを使用した複数の列に基づく複数の条件

col1> a(float)の値とcol2の値 - col3の値が0,b(float)の場合、col 4の値は文字列、そうでない場合は他の文字列です。

私は今や非常に多くの異なる方法を試しています。私がオンラインで見つけたものはすべて、1つの条件に依存していました。

私のコード例では常にエラーが発生します。 Seriesの真理値はあいまいです。 a.empty、a.bool()、a.item()、a.any()またはa.all()を使用します。

ここにコードがあります。成功しなかったいくつかのバリエーションを試しました。

df = pd.DataFrame() 

df['A'] = range(10) 
df['B'] = range(11,21,1) 
df['C'] = range(20,10,-1) 

borderE = 3. 
ex = 0. 

#print df 

df['color'] = np.where(all([df.A < borderE, df.B - df.C < ex]), 'r', 'b') 

はところで:私は、事前に おかげで...それをどのように扱うか、それが言うこと、理解しなく!

答えて

6

選択基準をBoolean indexingを使用しています:

df['color'] = np.where(((df.A < borderE) & ((df.B - df.C) < ex)), 'r', 'b') 

>>> df 
    A B C color 
0 0 11 20  r 
1 1 12 19  r 
2 2 13 18  r 
3 3 14 17  b 
4 4 15 16  b 
5 5 16 15  b 
6 6 17 14  b 
7 7 18 13  b 
8 8 19 12  b 
9 9 20 11  b 
1

機能でIFをラップし、それを適用します。

def color(row): 
    borderE = 3. 
    ex = 0. 
    if (row.A > borderE) and(row.B - row.C < ex) : 
     return "somestring" 
    else: 
     return "otherstring" 

df.loc[:, 'color'] = df.apply(color, axis = 1) 

収量:

A B C  color 
0 0 11 20 otherstring 
1 1 12 19 otherstring 
2 2 13 18 otherstring 
3 3 14 17 otherstring 
4 4 15 16 somestring 
5 5 16 15 otherstring 
6 6 17 14 otherstring 
7 7 18 13 otherstring 
8 8 19 12 otherstring 
9 9 20 11 otherstring 
関連する問題