2017-05-04 8 views
0

このコードは、すべての行を循環して 'is_color'関数を呼び出すことによって機能します。この関数は、「青」、たとえば、条件がパンダのforループのセルに値を割り当てる正しい方法

私はもともと働いていたが、私はそれが生産できるようにするまでに必要な SettingWithCopyWarningを投げた df['color'].iloc[i] = 'blue'をしていた
import numpy as np 
import pandas as pd 

def is_color(df): 

    df['color'] = np.nan 
    def blue(i): 
     is_blue = True # some more complex condition 
     if is_blue: 
      #df['color'].iloc[i] = 'blue' 
      df.set_value(i, 'color', 'blue') 

    for i in range(len(df)): 

     blue(i) 

     # not included i this example 
     #green(i) 
     #orange(i) 
     #purple(i) 
     #yellow(i) 

    return df 

を満たしている場合には、i番目の行の値をチェックし、色を割り当て

import numpy as np 
import pandas as pd 

def is_color(df): 

    df['color'] = np.nan 
    def blue(i, df): 
     is_blue = True # some more complex condition 
     if is_blue: 
      #df['color'].iloc[i] = 'blue' 
      return df.set_value(i, 'color', 'blue') 
     return df 

    for i in range(len(df)): 

     df = blue(i, df) 

     # not included i this example 
     #df = green(i, df) 
     #df = orange(i, df) 

    return df 

私は私の元のコードがきれいだったように、しかし、これを行うにはきれいな方法があると感じる。私は私が考えるこのようにそれを行う必要がありValueError: could not convert string to float: blueを投げることがdf.set_value(i, 'color', 'blue')を試してみましたか?

+0

はあなたが私たちのサンプルを表示することができますあなたのデータフレーム? – Hackaholic

+0

あなたは 'DF [ '色']に'のDF [ '色'] = np.nan'を変更= '' 'またはそれを削除する必要があります。 – jezrael

+0

本当にループが必要ですか? – jezrael

答えて

0

多くの条件がifelifelseとカスタム機能で可能な使用applyの場合:

サンプル:

df = pd.DataFrame({'A':[10,20,31], 
        'B':[4,5,6]}) 

print (df) 

def is_color(x): 
    if x < 15: 
     x = 'blue' 
    elif (x > 15) and (x < 25): 
     x = 'green' 
    else: 
     x = 'nothing' 
    return (x) 


df['color'] = df['A'].apply(is_color) 
print (df) 
    A B color 
0 10 4  blue 
1 20 5 green 
2 31 6 nothing 

同様のソリューション:

def is_color(x): 
    a = 'nothing' 
    if x < 15: 
     a = 'blue' 
    if (x > 15) and (x < 25): 
     a = 'green' 
    return (a) 


df['color'] = df['A'].apply(is_color) 
print (df) 
    A B color 
0 10 4  blue 
1 20 5 green 
2 31 6 nothing 
関連する問題