正文
在Python运行过程中遇到了如下错误:
TypeError: ‘list’ object is not callable
# 使用列表创建一个DataFrame
list = ["Gamer47", "Shox", "Simple"]
df = pd.DataFrame(list)
print("df = %s" % df)
# 使用Series字典对象生成DataFrame
df2 = pd.DataFrame({'A': 1.,
'B': pd.Timestamp('20130102'),
'C': pd.Series(1, index = list(range(4)), dtype = 'float32'),
'D': np.array([3] * 4, dtype = 'int32'),
'E': pd.Categorical(["test", "train", "test", "train"]),
'F': 'foo'})
print(f'df2 = {df2}')
代码运行后出错了,提示是TypeError: ‘list’ object is not callable
Traceback (most recent call last):
File "D:/code/求和.py", line 78, in <module>
'C': pd.Series(1, index = list(range(4)), dtype = 'float32'),
TypeError: 'list' object is not callable
callable()是python的内置函数,用来检查对象是否可被调用,可被调用指的是对象能否使用()括号的方法调用,类似于iterable()
在如上代码中,由于变量list和函数list重名了,所以函数在使用list函数时,发现list是一个定义好的列表,而列表是不能被调用的,因此抛出一个类型错误
解决办法
把变量名list修改为其他变量名(不能与函数名重复),运行结果正常
lst = ["Gamer47", "Shox", "Simple"]
df = pd.DataFrame(lst)
print("df = %s" % df)
因此,在命名变量时要注意,应避免和python的函数名、关键字冲突。
原文链接:https://blog.csdn.net/lvsehaiyang1993/article/details/80667921