Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Ctrl+K

pandas.DataFrame.xs#

DataFrame.xs(key,axis=0,level=None,drop_level=True)[source]#

Return cross-section from the Series/DataFrame.

This method takes akey argument to select data at a particularlevel of a MultiIndex.

Parameters:
keylabel or tuple of label

Label contained in the index, or partially in a MultiIndex.

axis{0 or ‘index’, 1 or ‘columns’}, default 0

Axis to retrieve cross-section on.

levelobject, defaults to first n levels (n=1 or len(key))

In case of a key partially contained in a MultiIndex, indicatewhich levels are used. Levels can be referred by label or position.

drop_levelbool, default True

If False, returns object with same levels as self.

Returns:
Series or DataFrame

Cross-section from the original Series or DataFramecorresponding to the selected index levels.

See also

DataFrame.loc

Access a group of rows and columns by label(s) or a boolean array.

DataFrame.iloc

Purely integer-location based indexing for selection by position.

Notes

xs can not be used to set values.

MultiIndex Slicers is a generic way to get/set values onany level or levels.It is a superset ofxs functionality, seeMultiIndex Slicers.

Examples

>>>d={'num_legs':[4,4,2,2],...'num_wings':[0,0,2,2],...'class':['mammal','mammal','mammal','bird'],...'animal':['cat','dog','bat','penguin'],...'locomotion':['walks','walks','flies','walks']}>>>df=pd.DataFrame(data=d)>>>df=df.set_index(['class','animal','locomotion'])>>>df                           num_legs  num_wingsclass  animal  locomotionmammal cat     walks              4          0       dog     walks              4          0       bat     flies              2          2bird   penguin walks              2          2

Get values at specified index

>>>df.xs('mammal')                   num_legs  num_wingsanimal locomotioncat    walks              4          0dog    walks              4          0bat    flies              2          2

Get values at several indexes

>>>df.xs(('mammal','dog','walks'))num_legs     4num_wings    0Name: (mammal, dog, walks), dtype: int64

Get values at specified index and level

>>>df.xs('cat',level=1)                   num_legs  num_wingsclass  locomotionmammal walks              4          0

Get values at several indexes and levels

>>>df.xs(('bird','walks'),...level=[0,'locomotion'])         num_legs  num_wingsanimalpenguin         2          2

Get values at specified column and axis

>>>df.xs('num_wings',axis=1)class   animal   locomotionmammal  cat      walks         0        dog      walks         0        bat      flies         2bird    penguin  walks         2Name: num_wings, dtype: int64

[8]ページ先頭

©2009-2025 Movatter.jp