我无法弄清楚 pandas pd.pivot_table 如何存储或引用表的行/索引中变量的名称 和列;从查看源代码来看,它似乎没有将它们存储在任何属性中的任何地方,尽管 str(tbl) 显然是从某个地方获取它们的。花了几个小时试图弄清楚但不能:
仅供引用 类层次结构是:pivot_table (tools/pivot.py) 是 class DataFrame (core/frame.py) 的一个实例,继承自 -> NDFrame (core/generic .py) -> PandasObject (core/base.py) -> StringMixin。但是在浏览了所有这些源之后,我没有看到存储在该层次结构中任何位置的变量名?!
import pandas as pd
import numpy as np
df = pd.DataFrame({'foo': [1,2,2,3,2,3,1,3],
'bar': [8,6,8,7,7,6,6,7],
'baz': np.random.rand(8).round(2)})
tbl = df.pivot_table(values='baz', index='foo', columns='bar')
# where are the names 'foo', 'bar' stored inside the attributes of tbl?
# bar 6 7 8
# foo
# 1 0.39 NaN 0.97
# 2 0.76 0.240 0.97
# 3 0.18 0.245 NaN
请您参考如下方法:
'foo'和'bar'分别存储为tbl的索引名和列索引名。索引对象不同于 DataFrame/NDFrame 对象。
>>> tbl.index.name
'foo'
>>> tbl.columns.name
'bar'
设置.name 属性的源代码相关部分是here .
