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))
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.