我正在使用 .xs 或 .loc(它们的行为似乎相同)按索引提取数据框的一个子集。当我的条件检索多行时,结果仍然是一个数据框。当只检索到一行时,它会自动转换为一系列。我不想要这种行为,因为这意味着我需要在下游处理多个案例(不同的方法集可用于系列与数据框)。
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
我可以手动将该系列转换回数据框,但这看起来很麻烦,而且还需要进行案例测试以确定我是否应该这样做。有没有一种更简洁的方法来让数据框回到开始?
最佳答案
IIUC,你可以简单地添加大括号,[]
,并使用.loc
:
>>> df.loc["two"]
a 4
c 14
Name: two, dtype: int64
>>> type(_)
<class 'pandas.core.series.Series'>
>>> df.loc[["two"]]
a c
b
two 4 14
[1 rows x 2 columns]
>>> type(_)
<class 'pandas.core.frame.DataFrame'>
这可能会让您想起 numpy
高级索引的工作原理:
>>> a = np.arange(9).reshape(3,3)
>>> a[1]
array([3, 4, 5])
>>> a[[1]]
array([[3, 4, 5]])
现在这可能需要对代码进行一些重构,以便您始终使用列表进行访问,即使该列表只有一个元素,但它在实践中对我来说效果很好。
关于python - 提取单行时如何保留 Pandas 数据框身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21053078/