gpt4 book ai didi

python - 按标签选择的 Pandas 有时会返回 Series,有时会返回 DataFrame

转载 作者:行者123 更新时间:2023-11-28 19:10:59 24 4
gpt4 key购买 nike

在 Pandas 中,当我选择一个在索引中只有一个条目的标签时,我得到一个系列,但是当我选择一个有多个条目的条目时,我得到一个数据框。

这是为什么呢?有没有办法确保我始终取回数据框?

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。还有其他方法,但我认为这是最干净的方法。

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

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

关于python - 按标签选择的 Pandas 有时会返回 Series,有时会返回 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40248695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com