【问题标题】:How to iterate through pandas series with 2 indexes?如何使用 2 个索引遍历 pandas 系列?
【发布时间】:2023-02-10 22:24:40
【问题描述】:

我有一个系列my_series,看起来像这样:

Index           Date      
12345           2019-01-03     14.0
                2019-01-04     65.0
                2019-01-05     81.0
                                
23456           2019-12-14    21.0
                2019-12-15    51.0
                2019-12-16    55.0

我想通过选择两个索引来查看它的值,因为我需要对每个值执行一个操作。

目前我正在做的是这样的:

a_dict = {
    index : my_series[index,date] * 2 for index,date in my_series
}

但不断收到此错误:

'numpy.float64' 对象不可迭代

【问题讨论】:

    标签: python pandas multi-index


    【解决方案1】:

    level='Index'上使用groupby

    df.groupby(level='Index').apply(function)
    

    或者在字典理解中:

    out = {k: function(g) for k, g in df.groupby(level='Index')}
    

    【讨论】:

    • 谢谢,但这并没有像我预期的那样工作:有问题的系列已经来自分组数据框中的一些聚合,但它有 2 个索引。我需要通过遍历它们来访问这些浮点数。
    • @backer 你能提供一个可重现的输入和匹配的预期输出吗?
    【解决方案2】:

    好的,得到了​​我需要的东西,所以我发布了我是如何解决它的,以防其他人需要。

    所以基本上我是想访问for index,date in my_series, 变量 index 包括列“索引”和“日期”。我必须单独访问“索引”值,所以我要做的是:

     a_dict = {
          index[0] : value * 2 for index,value in my_series.items()
    }
    

    在这种情况下,index 指的是我系列中的“索引”和“日期”。通过循环 my_seires.items() 我可以访问索引和我感兴趣的值。不确定我的意思是否清楚,但我是 Python Pandas 的新手哈哈

    【讨论】:

      猜你喜欢
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 2022-10-20
      • 2016-03-26
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 2020-08-09
      相关资源
      最近更新 更多