考虑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
和 columns
df
的轴与 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')
最佳答案
使用.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')
关于python - 通过轴号访问 pandas 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40027233/