csv TypeError:'method'对象在python jupyter notebook中不可下标

raogr8fs  于 2023-04-09  发布在  Python
关注(0)|答案(2)|浏览(186)

我收到错误“TypeError:'method' object is not subscriptable”,我还没有看到任何解决方案能够解决我的问题。
代码:

new_high_blood_pressure = df.groupby["age"]("high_blood_pressure").reset_index()
new_high_blood_pressure

我所期望的:

age | high_blood_pressure
11  | 1
22  | 0
33  | 0
44  | 1
55  | 1

我得到了什么:

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_8088\2358215825.py in <module>
      1 #On this new data frame perform group operation as per age and create new dataframe
----> 2 new_high_blood_pressure = df.groupby["age"]("high_blood_pressure").reset_index()
      3 new_high_blood_pressure

TypeError: 'method' object is not subscriptable

谢谢大家。

2ul0zpep

2ul0zpep1#

groupby是一个方法,所以你应该使用( )而不是[ ],但是当你选择一个列时,使用[ ]而不是( )
但是,您必须对组应用一个函数(max,min,mean,...或自定义函数)。下面是max的示例:

df.groupby('age')['high_blood_pressure'].max()
5m1hhzi4

5m1hhzi42#

当您尝试在Python中的方法对象上使用索引运算符“[]”时,通常会发生此错误。
当你引用一个对象的一个方法,但不通过在方法名后包括括号来调用它时,就会创建一个方法对象。方法对象是对实际方法的引用,但它不执行方法本身。
若要修复此错误,您需要确保使用适当的参数和括号调用方法。请检查是否未使用方括号“[]”访问方法对象的元素。
例如,考虑以下代码:

class MyClass:
    def my_method(self):
        return "Hello, World!"

    obj = MyClass()
    method_obj = obj.my_method
    result = method_obj[0]  # this will cause the TypeError

在上面的代码中,method_obj是对MyClass对象的my_method函数的引用。然而,当我们尝试使用方括号访问method_obj的第一个元素时,我们会得到TypeError,因为method_obj不是可以索引的列表或元组。
为了修复这个错误,我们应该调用带括号的my_method函数来执行该方法并获取返回值:

result = method_obj()  # this will execute the method and store the return value 
in `result`

通过在method_obj后面包含括号,我们调用方法并获取其返回值,而不是试图索引方法对象。

相关问题