Search code examples
pythonpandasdata-analysis

Adding entries in dataframe for reverse index order


I have to make bar plot of data from a multindex panda dataframe. This dataframe has the following structure :

        value
  1 2    25
    3    96
    4    -12
  ...
  2 3    -25 
    4    -30
  ...
  3 4    541
    5    396
    6    14
  ...

Note that there is a value for index entry (1,2) but no value for (2,1). There is always an index entry (x,y) with y > x and I'd like to create an entry (y,x) for every entry (x,y) having the same value. Basically, I'd like to make my dataframe matrix symmetric. I've tried by switching the level of the indexes and then concatenating the results into a new dataframe but I can't obtain the result I want. Maybe I could do it with a for loop but I'm pretty sure there is a better way to do that... Do you know how to do that efficiently ?


Solution

  • Try using, pd.concat and swaplevel :

    pd.concat([df, df.swaplevel(0,1)])
    

    Output:

         value
    x y       
    1 2     25
      3     96
      4    -12
    2 3    -25
      4    -30
    3 4    541
      5    396
      6     14
    2 1     25
    3 1     96
    4 1    -12
    3 2    -25
    4 2    -30
      3    541
    5 3    396
    6 3     14