DataFrame中的条件列:哪里出错?

时间:2017-02-03 11:55:35

标签: python pandas dataframe

让我们从带有数字列dfpSpS0的Pandas DataFrame pE开始:

import pandas as pd
df = pd.DataFrame([[0.1,0.2,0.7],[0.3,0.6,0.1],[0.9,0.1,0.0]], 
                  columns=['pS','pE','pS0'])

我们想要建立一个列,指示前三个中的哪一个占主导地位。我是这样实现的:

def class_morph(x):
    y = [x['pE'],x['pS'],x['pS0']]
    y.sort(reverse=True)
    if (y[0] == y[1]):
        return 'U'
    elif (x['pE'] == y[0]):
        return 'E'
    elif (x['pS'] == y[0]):
        return 'S'
    elif (x['pS0'] == y[0]):
        return 'S0'

df['Morph'] = df.apply(class_morph, axis=1)

这给出了正确的结果:

enter image description here

但我最初的尝试如下:

def class_morph(x):
    if (x['pE'] > np.max(x['pS'],x['pS0'])):
        return 'E'
    elif (x['pS'] > np.max(x['pE'],x['pS0'])):
        return 'S'
    elif (x['pS0'] > np.max(x['pS'],x['pE'])):
        return 'S0'
    else:
        return 'U'

哪回错了:

enter image description here

有人可以向我解释我第一次尝试时的错误吗?

0 个答案:

没有答案