Nik*_*wal 2 python pandas pandas-groupby
我的数据框是 -
id score
1 50
2 88
3 44
4 77
5 93
Run Code Online (Sandbox Code Playgroud)
我希望我的数据框看起来像 -
id score is_good
1 50 low
2 88 high
3 44 low
4 77 medium
5 93 high
Run Code Online (Sandbox Code Playgroud)
我已经完成了以下代码 -
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)
Run Code Online (Sandbox Code Playgroud)
我认为逻辑很好,但代码不起作用。也许我们可以使用地图功能。
这是一个很好的用例pd.cut:
df['is_good'] = pd.cut(df.score,
[-np.inf,50,80,np.inf],
labels=['low','medium','high'])
Run Code Online (Sandbox Code Playgroud)
print(df)
id score is_good
0 1 50 low
1 2 88 high
2 3 44 low
3 4 77 medium
4 5 93 high
Run Code Online (Sandbox Code Playgroud)