Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pandas数据帧中多if-else条件的实现_Python_Pandas_Pandas Groupby - Fatal编程技术网

Python pandas数据帧中多if-else条件的实现

Python pandas数据帧中多if-else条件的实现,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,我的数据框是- id score 1 50 2 88 3 44 4 77 5 93 我希望我的数据框看起来像- id score is_good 1 50 low 2 88 high 3 44 low 4 77 medium 5

我的数据框是-

id       score
1          50
2          88
3          44
4          77
5          93
我希望我的数据框看起来像-

id       score      is_good
1          50        low
2          88        high
3          44        low
4          77        medium
5          93        high
我已经完成了以下代码-

def selector(row):
    if row['score'] >= 0 and row['score'] <= 50 :
        return "low"
    elif row['score'] > 50 and row['score'] <=80 :
        return "medium"
    else:
        return "high"

x['is_good'] = x.apply(lambda row : selector(x), axis=1)
def选择器(行):

如果行['score']>=0,行['score']50和行['score']这是一个很好的用例:


你可以用+



您的代码中存在错误,原因是:

x['is_good'] = x.apply(lambda row : selector(x), axis=1)
应该是:

x['is_good'] = x.apply(lambda row : selector(row), axis=1)

它采用的是序列而不是行,这就是您出现错误的原因。

您可以指定“代码不工作”的含义吗?df.score.max()。np.inf会更快吗?我想我读到一些关于在pd.cut中这不是一个好主意的东西。虽然不确定@pinegulfI认为我更喜欢它:)@pinegulf@yatu,需要什么
np.inf
你能添加一些细节吗?
np.inf
只是考虑一下边缘箱。所以从-inf到50,这是很低的。80到inf的值为high@SushanthSushanth-获取错误“AttributeError:'函数'对象没有属性'between'”
import numpy as np

df['is_good'] = (
    np.where(df.score.between(0, 50), "low",
             np.where(df.score.between(51, 80), "medium", "high"))
)
   id  score is_good
0   1     50     low
1   2     88    high
2   3     44     low
3   4     77  medium
4   5     93    high
x['is_good'] = x.apply(lambda row : selector(x), axis=1)
x['is_good'] = x.apply(lambda row : selector(row), axis=1)