+-
python – 从pandas数据框中获取包括索引名称的列名
假设我们的数据框的索引可能有一个名称:

df = pd.DataFrame({'a':[1,2,3],'b':[3,6,1], 'c':[2,6,0]})
df = df.set_index(['a'])

   b  c
a      
1  3  2
2  6  6

获取包含索引名称的列名称的最佳方法是什么(如果存在).

在这种情况下,调用df.columns.tolist()不包含索引名称并返回[‘b’,’c’],我想获得[‘a’,’b’,’c’].

最佳答案
可以为呼叫临时重置索引:

df.reset_index().columns.tolist()

如果列表中不显示空索引名称,请有条件地执行reset_index():

(df.reset_index() if df.index.name else df).columns.tolist()
点击查看更多相关文章

转载注明原文:python – 从pandas数据框中获取包括索引名称的列名 - 乐贴网