Search code examples
pythonpandasindexingmulti-index

Add/Modify index of Pandas DataFrame


I have a multi-index Pandas DataFrame data which has indexes ID and Frequency (Hz), and column name Angles. For each ID data set , the Frequency index ranges from 4 to 1000 in steps of 4.

Angles                            1          2          3          4  \
ID             Frequency                                               
11111          4.0              2.1        5.4        3.1        6.4   
               8.0              1.1        7.9        4.5        6.3   
               12.0             5.2        5.1        9.6       11.2
               16.0             6.7        6.1        2.9        7.3   
               20.0             1.1        6.1        4.7        6.9
...                             ...        ...        ...        ...  
11120          992.0            9.2        5.4        2.7        9.2
               996.0            8.1        8.9        3.1        4.5
               1000.0           2.1        1.8        5.5        8.4

I want to add an additional Rad/s index column which multiples each value in the Frequency index by 2π, giving something like this:

Angles                                 1          2          3          4  \
ID          Frequency    Rad/s                                              
11111       4.0          25.1        2.1        5.4        3.1        6.4   
            8.0          50.3        1.1        7.9        4.5        6.3   
            12.0         75.4        5.2        5.1        9.6       11.2
            16.0         100.5       6.7        6.1        2.9        7.3   
            20.0         125.7       1.1        6.1        4.7        6.9
...                                  ...        ...        ...        ...  
11120       992.0        6232.9      9.2        5.4        2.7        9.2
            996.0        6258.1      8.1        8.9        3.1        4.5
            1000.0       6283.2      2.1        1.8        5.5        8.4

I've looked into changing the Frequency index into a regular column and applying the multiplication after but I was wondering if there is a better way of doing this?


Solution

  • You can use get_level_values, rename and multiple it first and then use set_index with parameter append=True:

    new = df.index.get_level_values('Frequency').rename('Rad/s') * 2 * np.pi
    df = df.set_index(new, append=True)
    print (df)
                                   1    2    3     4
    ID    Frequency Rad/s                           
    11111 4.0       25.132741    2.1  5.4  3.1   6.4
          8.0       50.265482    1.1  7.9  4.5   6.3
          12.0      75.398224    5.2  5.1  9.6  11.2
          16.0      100.530965   6.7  6.1  2.9   7.3
          20.0      125.663706   1.1  6.1  4.7   6.9
    11120 992.0     6232.919825  9.2  5.4  2.7   9.2
          996.0     6258.052566  8.1  8.9  3.1   4.5
          1000.0    6283.185307  2.1  1.8  5.5   8.4