考虑一下pd.Panel pn和pd.DataFrame df
import pandas as pd
import numpy as np
pn = pd.Panel(np.arange(27).reshape(3, 3, 3), list('XYZ'), list('abc'), list('ABC'))
pn.to_frame().rename_axis('item', 1).unstack()

df = pd.DataFrame(np.arange(9).reshape(3, 3), list('abc'), list('ABC'))
df

我可以用items访问pn的pn.items轴,用df.columns访问df的columns轴。
问题
但是,如何获得items轴的pn与数字0和minor_axis轴与数字2?有了许多接受参数axis=0的方法,我想有一种通过数字直接访问轴的方法。
我做了什么,
自定义函数
def get_axis(obj, axis=0):
if isinstance(obj, pd.Panel):
m = pd.Series(['items', 'major_axis', 'minor_axis'])
else:
m = pd.Series(['index', 'columns'])
return obj.__getattribute__(m.loc[axis])
print(get_axis(pn, 2))
print(get_axis(pn, 1))
print(get_axis(pn, 0))
print(get_axis(df, 1))
print(get_axis(df, 0))Index([u'A', u'B', u'C'], dtype='object')
Index([u'a', u'b', u'c'], dtype='object')
Index([u'X', u'Y', u'Z'], dtype='object')
Index([u'A', u'B', u'C'], dtype='object')
Index([u'a', u'b', u'c'], dtype='object')发布于 2016-10-13 19:37:24
使用.axes返回索引轴标签和列轴标签的列表,然后可以通过片表示法访问它。
pn.axes
#[Index(['X', 'Y', 'Z'], dtype='object'),
# Index(['a', 'b', 'c'], dtype='object'),
# Index(['A', 'B', 'C'], dtype='object')]然后,您可以提供切片来检索对象:
pn.axes[0]
#Index(['X', 'Y', 'Z'], dtype='object')
df.axes[0]
#Index(['a', 'b', 'c'], dtype='object')https://stackoverflow.com/questions/40027233
复制相似问题