设置Pandas DataFrame索引名称失败,报'NoneType'不可调用错误
解决Pandas DataFrame设置索引名称的TypeError问题
错误原因
报错的核心问题是:df.index.name是DataFrame索引的属性,不是可调用的方法。初始状态下这个属性值为None,用括号()去调用它,就会触发TypeError: 'NoneType' object is not callable。
修正方案
把调用属性的写法改成赋值操作即可,有两种常用方式:
方式1:直接给index.name赋值
这是最直接的写法:
import numpy as np import pandas as pd np.random.seed(121) randArr = np.random.randint(0,100,20).reshape(5,4) df = pd.DataFrame(randArr, np.arange(101,106,1), ['PDS','Algo','SE','INS']) # 修正:把调用改成赋值 df.index.name = 'RollNo' print(df)
方式2:使用rename_axis方法(支持链式调用)
如果需要链式操作其他DataFrame方法,可以用rename_axis:
import numpy as np import pandas as pd np.random.seed(121) randArr = np.random.randint(0,100,20).reshape(5,4) df = pd.DataFrame(randArr, np.arange(101,106,1), ['PDS','Algo','SE','INS'])\ .rename_axis('RollNo') # 链式设置索引名称 print(df)
原错误代码及报错信息
错误代码
import numpy as np import pandas as pd np.random.seed(121) randArr =np.random.randint(0,100,20).reshape(5,4) df =pd.DataFrame(randArr,np.arange(101,106,1),['PDS','Algo','SE','INS']) df.index.name('RollNo') print(df)
报错信息
Traceback (most recent call last):
File "D:/Education/4th year/1st sem/Machine Learning Lab/1st Lab/python/pandas/dfCondSel.py", line 25, in
df.index.name('RollNo')
TypeError: 'NoneType' object is not callable
内容的提问来源于stack exchange,提问作者Subrata Biswas
相关产品推荐
相关产品推荐

