w3resource

Pandas Series: xs() function

Cross-section from the Series/DataFrame in Pandas

The xs() function is used to get cross-section from the Series/DataFrame.

This method takes a key argument to select data at a particular level of a MultiIndex.

Syntax:

Series.xs(self, key, axis=0, level=None, drop_level=True)

Parameters:

Name Description Type/Default Value Required / Optional
key Label contained in the index, or partially in a MultiIndex.
 label or tuple of label Required
axis Axis to retrieve cross-section on. {0 or ‘index’, 1 or ‘columns’}
Default Value: 0
Required
level In case of a key partially contained in a MultiIndex, indicate which levels are used. Levels can be referred by label or position. object
Default Value: defaults to first n levels (n=1 or len(key))
Required
drop_level If False, returns object with same levels as self. bool
Default Value: True
Required

Returns: Series or DataFrame
Cross-section from the original Series or DataFrame corresponding to the selected index levels.

Notes:

xs can not be used to set values.

MultiIndex Slicers is a generic way to get/set values on any level or levels.

Example:

Python-Pandas Code:

import numpy as np
import pandas as pd
d = {'num_legs': [4, 4, 4, 2, 2],
     'num_wings': [0, 0, 0, 2, 2],
     'class': ['mammal', 'mammal', 'mammal', 'bird', 'bird'],
     'animal': ['tiger', 'lion', 'fox', 'eagle', 'penguin'],
     'locomotion': ['walks', 'walks', 'walks', 'flies', 'walks']}
df = pd.DataFrame(data=d)
df = df.set_index(['class', 'animal', 'locomotion'])
df

Output:

                                num_legs  num_wings
class  animal  locomotion                     
mammal tiger   walks              4          0
       lion    walks              4          0
       fox     walks              4          0
bird   eagle   flies              2          2
       penguin walks              2          2

Example - Get values at specified index:

Python-Pandas Code:

import numpy as np
import pandas as pd
d = {'num_legs': [4, 4, 4, 2, 2],
     'num_wings': [0, 0, 0, 2, 2],
     'class': ['mammal', 'mammal', 'mammal', 'bird', 'bird'],
     'animal': ['tiger', 'lion', 'fox', 'eagle', 'penguin'],
     'locomotion': ['walks', 'walks', 'walks', 'flies', 'walks']}
df = pd.DataFrame(data=d)
df = df.set_index(['class', 'animal', 'locomotion'])
df.xs('mammal')

Output:

                                num_legs	num_wings
animal	locomotion		
tiger	      walks	                        4	0
lion	      walks	                        4	0
fox	      walks	                        4	0

Example - Get values at several indexes:

Python-Pandas Code:

import numpy as np
import pandas as pd
d = {'num_legs': [4, 4, 4, 2, 2],
     'num_wings': [0, 0, 0, 2, 2],
     'class': ['mammal', 'mammal', 'mammal', 'bird', 'bird'],
     'animal': ['tiger', 'lion', 'fox', 'eagle', 'penguin'],
     'locomotion': ['walks', 'walks', 'walks', 'flies', 'walks']}
df = pd.DataFrame(data=d)
df = df.set_index(['class', 'animal', 'locomotion'])
df.xs(('mammal', 'fox'))

Output:

                   num_legs	num_wings
locomotion		
walks	                   4	0

Example - Get values at specified index and level:

Python-Pandas Code:

import numpy as np
import pandas as pd
d = {'num_legs': [4, 4, 4, 2, 2],
     'num_wings': [0, 0, 0, 2, 2],
     'class': ['mammal', 'mammal', 'mammal', 'bird', 'bird'],
     'animal': ['tiger', 'lion', 'fox', 'eagle', 'penguin'],
     'locomotion': ['walks', 'walks', 'walks', 'flies', 'walks']}
df = pd.DataFrame(data=d)
df = df.set_index(['class', 'animal', 'locomotion'])
df.xs('lion', level=1)

Output:

                   num_legs	num_wings
class	locomotion		
mammal	walks	       4	0

Example - Get values at several indexes and levels:

Python-Pandas Code:

import numpy as np
import pandas as pd
d = {'num_legs': [4, 4, 4, 2, 2],
     'num_wings': [0, 0, 0, 2, 2],
     'class': ['mammal', 'mammal', 'mammal', 'bird', 'bird'],
     'animal': ['tiger', 'lion', 'fox', 'eagle', 'penguin'],
     'locomotion': ['walks', 'walks', 'walks', 'flies', 'walks']}
df = pd.DataFrame(data=d)
df = df.set_index(['class', 'animal', 'locomotion'])
df.xs(('bird', 'walks'),
      level=[0, 'locomotion'])

Output:

                   num_legs  num_wings
animal                      
penguin               2          2

Example - Get values at specified column and axis:

Python-Pandas Code:

import numpy as np
import pandas as pd
d = {'num_legs': [4, 4, 4, 2, 2],
     'num_wings': [0, 0, 0, 2, 2],
     'class': ['mammal', 'mammal', 'mammal', 'bird', 'bird'],
     'animal': ['tiger', 'lion', 'fox', 'eagle', 'penguin'],
     'locomotion': ['walks', 'walks', 'walks', 'flies', 'walks']}
df = pd.DataFrame(data=d)
df = df.set_index(['class', 'animal', 'locomotion'])
df.xs('num_wings', axis=1)

Output:

class   animal   locomotion
mammal  tiger    walks         0
        lion     walks         0
        fox      walks         0
bird    eagle    flies         2
        penguin  walks         2
Name: num_wings, dtype: int64

Previous: Get item and drop from frame
Next: Addition of Pandas series and other



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/pandas/series/series-xs.php