Jason
Jason

Reputation: 323

`df.loc` return series instead dataframe

I have a DataFrame

import pandas as pd
import numpy as np

index = pd.MultiIndex.from_product([["A", "B"], ["AA", "BB"]])
columns = pd.MultiIndex.from_product([["X", "Y"], ["XX", "YY"]])

df = pd.DataFrame([[1,2,3,4],
                   [5,6,7,8],
                   [9,10,11,12],
                   [13,14,15,16]], index = index, columns = columns)

and a slice slice_ = ((slice(None), slice(None)), ("X", "XX")). Unfortunately df.loc[slice_] returns Series instead DataFrame. How can I fix that?

Upvotes: 1

Views: 370

Answers (2)

mozway
mozway

Reputation: 260790

Two options.

Either wrap the columns' slice in []:

slice_ = ((slice(None), slice(None)), [("X", "XX")])
df.loc[slice_] 

or, if you don't want to alter the slice, convert back to_frame

slice_ = ((slice(None), slice(None)), ("X", "XX"))
df.loc[slice_].to_frame()

output:

       X
      XX
A AA   1
  BB   5
B AA   9
  BB  13

Upvotes: 3

bzu
bzu

Reputation: 1594

Try with:

df.loc[((slice(None), slice(None)), [("X", "XX")])]

Upvotes: 2

Related Questions