'int' 对象在 if 语句后不可下标 [英] 'int' object is not subscriptable after if statement
本文介绍了'int' 对象在 if 语句后不可下标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个数据框:
import pandas as pd
df = pd.DataFrame({'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'score': [1, 3, 4, 5, 2]})
我想根据分数"列中的条件创建一个新列.
And I want to create a new column based on the conditions in the 'score' column.
我是这样试的
df['happiness'] = df['score']
def are_you_ok(df):
if df['happiness'] >= 4:
return 'happy',
elif df['happiness'] <= 2:
return 'sad',
else:
return 'ok'
df['happines'] = df['happiness'].apply(are_you_ok)
df
当我尝试运行它时,我得到的只是:
When I try to run that though, all I get is:
TypeError: 'int' object is not subscriptable
我可以不使用带有整数的这种函数吗?
Can I not use this kind of function with an integer?
推荐答案
听起来像您想要的 np.select
来自 numpy
import numpy as np
conds = [df.score >=4, df.score <=2]
choices = ['happy', 'sad']
df['happiness'] = np.select(conds, choices, default='ok')
>>> df
name score happiness
0 Jason 1 sad
1 Molly 3 ok
2 Tina 4 happy
3 Jake 5 happy
4 Amy 2 sad
注意:您可以通过使用 pandas.np
(或 pd.np
,取决于您导入熊猫的方式)来避免显式导入 numpy
只是 np
Note: you can avoid explicitly importing numpy
by using pandas.np
(or pd.np
, depending how you imported pandas) instead of just np
这篇关于'int' 对象在 if 语句后不可下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文