1
我使用.xs或.loc(他们似乎表现相同)通过索引提取我的数据框的一个子集。当我的条件检索多行时,结果保留一个数据框。当只检索一行时,它会自动转换为一系列。我不想要这种行为,因为这意味着我需要处理多个下游案例(可用于系列vs数据框的不同方法集)。如何在提取单个行时保留大熊猫数据框标识
In [1]: df = pd.DataFrame({'a':range(7), 'b':['one']*4 + ['two'] + ['three']*2,
'c':range(10,17)})
In [2]: df.set_index('b', inplace=True)
In [3]: df.xs('one')
Out[3]:
a c
b
one 0 10
one 1 11
one 2 12
one 3 13
In [4]: df.xs('two')
Out[4]:
a 4
c 14
Name: two, dtype: int64
In [5]: type(df.xs('two'))
Out [5]: pandas.core.series.Series
我可以在一系列手动转换回数据帧,但似乎繁琐,也需要用例测试,看看我是否应该这样做。有没有更简洁的方法来重新开始数据框?