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

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

问题描述

在 Pandas 中,当我选择一个索引中只有一个条目的标签时,我会返回一个系列,但是当我选择一个包含多个条目的条目时,我会返回一个数据框.

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天全站免登陆