Python Jupyter Notebook中TypeError: 'method' object is not subscriptable问题求助
解决TypeError: 'method' object is not subscriptable的问题
错误原因
你的代码存在两个关键问题:
- groupby调用方式错误:
groupby是DataFrame的方法,必须用圆括号()传递分组列,而非方括号[](方括号用于索引DataFrame的列)。 - 缺少聚合逻辑:分组后需要明确对
high_blood_pressure列执行的聚合操作(比如取首个值、求和等),否则无法生成结构化的结果集。
修正后的代码
结合你的预期输出(每个age对应唯一的high_blood_pressure值),使用以下代码:
new_high_blood_pressure = df.groupby("age")["high_blood_pressure"].first().reset_index() new_high_blood_pressure
如果原数据中每个age仅对应一行记录,也可以简化为:
new_high_blood_pressure = df.groupby("age", as_index=False)["high_blood_pressure"].first()
代码说明
df.groupby("age"):正确调用groupby方法,按age列分组。["high_blood_pressure"]:指定要处理的目标列。.first():提取每个分组中high_blood_pressure列的首个值(适配单值分组的场景)。.reset_index():将分组后的索引(age)转为普通列,匹配你的预期输出格式。
验证结果
运行修正后的代码,会得到如下格式的结果:
age | high_blood_pressure 11 | 1 22 | 0 33 | 0 44 | 1 55 | 1
内容的提问来源于stack exchange,提问作者LAKSHYA SINGH CHAUHAN
相关产品推荐
相关产品推荐

