Search code examples
pythonpandasmulti-index

How to iterate through pandas series with 2 indexes?


I have a series my_series that looks like this:

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

and I want to go through its values by selecting both indexes, because I need to perform an operation with each value.

Currently what I'm doing is something like this:

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

but keep getting this error:

'numpy.float64' object is not iterable


Solution

  • Ok, got what I needed, so I'm posting how I solved it in case anyone else is in need.

    So basically I was trying to access for index,date in my_series , the variable index included both cols "Index" and "Date". I had to access the 'Index' value alone, so what I had to do was:

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

    In this case, index refers to both "Index" and "Date" in my series. And by looping my_seires.items() I get to access both the indexes and my values of interest. Not sure if its clear what I mean, but I'm new to Python Pandas haha