piRSquared
piRSquared

Reputation: 294258

access pandas axes by axis number

consider the pd.Panel pn and 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()

enter image description here

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

df

enter image description here


I can access the items axis of pn with pn.items and the columns axis of df with df.columns.

Question
But how do I get the items axis of pn with the number 0 and minor_axis axis with the number 2? With as many methods that accept the parameter axis=0, I'm imagining there is a straight forward way to access axes via number.

What I've done
Custom function

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')

Upvotes: 2

Views: 673

Answers (1)

Nickil Maveli
Nickil Maveli

Reputation: 29711

Use .axes to return a list of the index axis labels as well as the column axis labels and then you could access it via slice-notation.

pn.axes
#[Index(['X', 'Y', 'Z'], dtype='object'),
# Index(['a', 'b', 'c'], dtype='object'),
# Index(['A', 'B', 'C'], dtype='object')]

Then, you could provide the slices to retrieve the objects:

pn.axes[0]
#Index(['X', 'Y', 'Z'], dtype='object')

df.axes[0]
#Index(['a', 'b', 'c'], dtype='object')

Upvotes: 2

Related Questions