【问题标题】:how to use pandas.Series.at with pandas.MultiIndex如何将 pandas.Series.at 与 pandas.MultiIndex 一起使用
【发布时间】:2020-06-08 14:56:33
【问题描述】:

pandas.Series.atpandas.MultiIndex 使用的正确方法是什么,或者它不受支持?

import pandas as pd # pd.__version__ == '0.25.1'

d1 = pd.Series([10, 20, 30], index=[0,1,2])
print(d1.at[1]) # works

d2 = pd.Series([10, 20, 30], index=pd.MultiIndex.from_product([[0], [0,1,2]]))
print(d2.at[(0,1)])
# ValueError: At based indexing on an non-integer index can only have non-integer indexers

d3 = pd.Series([10, 20, 30],
    index=pd.MultiIndex.from_product([[pd.Timestamp('2020-02-24')], [0,1,2]]))
print(d3.at[('2020-02-24',1)])
print(d3.at[(pd.Timestamp('2020-02-24'),1)])
# TypeError: _get_value() got multiple values for argument 'takeable'

以下是上述系列的打印输出:

>>> print(d1)
0    10
1    20
2    30
dtype: int64
>>> print(d2)
0  0    10
   1    20
   2    30
dtype: int64
>>> print(d3)
2020-02-24  0    10
            1    20
            2    30
dtype: int64

非常感谢您的帮助!

【问题讨论】:

    标签: python pandas series multi-index


    【解决方案1】:

    我们可以使用locIndexSlice

    print(d2.loc[pd.IndexSlice[0,1]])
    20
    

    【讨论】:

    • 我知道我可以使用loc 代替atd2.loc[(0,1)]d3.loc[('2020-02-24',1)] 都可以正常工作。我的问题是为什么相同的调用不适用于 at 以及如何解决它。
    • @S.V 这就是 at 和 iat 的工作原理~github.com/pandas-dev/pandas/issues/9259
    • 感谢您的链接!虽然我不明白其中的逻辑:为什么 at 带有 DataFrame 很好,但 Series 却不行:d2.to_frame().at[(0,1), 0]d3.to_frame().at[('2020-02-24',1), 0] 都可以快速工作并且没有任何错误消息。
    猜你喜欢
    • 2021-06-01
    • 2021-01-02
    • 1970-01-01
    • 2023-03-13
    • 2014-09-25
    • 2016-01-30
    • 2015-12-13
    • 2020-09-15
    • 2020-06-03
    相关资源
    最近更新 更多