通过标签选择的 pandas 有时返回Series,有时返回DataFrame [英] Pandas selecting by label sometimes return Series, sometimes returns DataFrame

查看:73
本文介绍了通过标签选择的 pandas 有时返回Series,有时返回DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Pandas中,当我选择一个索引中只有一个条目的标签时,我会得到一个Series,但是当我选择一个条目中只有一个条目时,我就会得到一个数据框.

In Pandas, when I select a label that only has one entry in the index I get back a Series, but when I select an entry that has more then one entry I get back a data frame.

那是为什么?有没有办法确保我总是能取回数据帧?

Why is that? Is there a way to ensure I always get back a data frame?

In [1]: import pandas as pd

In [2]: df = pd.DataFrame(data=range(5), index=[1, 2, 3, 3, 3])

In [3]: type(df.loc[3])
Out[3]: pandas.core.frame.DataFrame

In [4]: type(df.loc[1])
Out[4]: pandas.core.series.Series

推荐答案

允许该行为不一致,但是我认为很容易想到这种情况很方便.无论如何,要每次获取一个DataFrame,只需将一个列表传递给loc.还有其他方法,但我认为这是最干净的方法.

Granted that the behavior is inconsistent, but I think it's easy to imagine cases where this is convenient. Anyway, to get a DataFrame every time, just pass a list to loc. There are other ways, but in my opinion this is the cleanest.

In [2]: type(df.loc[[3]])
Out[2]: pandas.core.frame.DataFrame

In [3]: type(df.loc[[1]])
Out[3]: pandas.core.frame.DataFrame

这篇关于通过标签选择的 pandas 有时返回Series,有时返回DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆