Search code examples
python-3.xpandasmulti-index

How to fusion two indexes in a pandas DataFrame to create only one in Python


I have a DataFrame with two indexes (called Year and Month) and one column (PL):

GB.head()
Year  Month     PL
1997  1        707.272727
      2        -94.545455
      3         22.727273
      4       -244.545455
      5        467.272727

I need to fusion the values of the two indexes in one new column. The result should be this:

New Index       PL
1997-1        707.272727
1997-2        -94.545455
1997-3         22.727273
1997-4         -244.545455
1997-5         467.272727

I guess that the solution could be extract the values of each index, after that fusion them in a new column and establish that column as the new index. But I am lost with that.

Could someone help me with this please?

Thanks!


Solution

  • Use list comprehension with f-strings:

    df.index = [f'{a}-{b}' for a, b in df.index]