Home > Software engineering >  Python Pandas to_frame() KeyError after converting Series to DataFrame
Python Pandas to_frame() KeyError after converting Series to DataFrame

Time:01-06

When I try to access a multiindex dataframe after converting from series I get a KeyError.

xs works, loc doesn't work. What am I doing wrong? Thanks

from pandas import Series, MultiIndex

s=Series([1,2,3,4], name = 'val')

s.index = MultiIndex.from_product([['a','b'],['1','2']], names = ['x','y'])

print((s.index == s.to_frame().index).all())

print (s.loc[(slice(None), '1')])
print (s.xs('1', level=1))

print (s.to_frame().loc[(slice(None), '1')])
print (s.to_frame().xs('1', level=1))

CodePudding user response:

It will work this way:

print (s.to_frame().loc[(slice(None), '1'),'val'])

The reason is that with Series you do not need to specify a column label whereas in a pandas DataFrame this is required for the loc attribute.

  •  Tags:  
  • Related