0

I have the following df with index1 year and index2 type.

                data
     year type  

     2017 A     1.23
          B     5.51
     2018 A     1.53
          B     0.89

I want to rename the index year so that it says Year 0 and Year 1.

I tried the following:

    index_years = []
    for i in range(len(df.index.levels[0])):
        index_years.append("Year " + str(i))
    df.index.levels[0] = index_years

But I get the following error:

ERROR GIVEN: 'FrozenList' does not support mutable operations.

Then I tried this

    pd.MultiIndex.from_tuples([(x[0].apply("Year " + str(i) for i in range(len(df.index.levels[0]))), x[1]) for x in df.index])

But it gives an error "int" boject is not subscriptible

The result I want to obtain is:

                    data

     year    type  

     Year 0   A     1.23
              B     5.51
     Year 1   A     1.53
              B     0.89
user7440787
  • 831
  • 7
  • 22
  • Possible duplicate of [Pandas: Modify a particular level of Multiindex](https://stackoverflow.com/questions/29150346/pandas-modify-a-particular-level-of-multiindex) – user7440787 Jul 29 '19 at 14:16
  • could you please update your question with the expected answer. It is difficult to understand what you mean by `rename the index year so that it says Year 0 and Year 1.` – user7440787 Jul 31 '19 at 07:55

2 Answers2

0

There is a property called index.names that you can use to set the names. Here is an example:

import pandas as pd
df = pd.DataFrame({'year':['2017','2017', '2018', '2018'], 
                   'type':['A', 'B', 'A', 'B'], 
                   'data':[1.23,5.51, 1.53, 0.89]
                 })
df = df.set_index(['year', 'type'])

# Here is the code to modify the DataFrame as you wanted
df = df.reset_index() #reset index so you can access the year as a column and have an integer index you can use
df.year = df.index.map(lambda x: f'year {x}') #map using a function to create new values for year that you need

df = df.set_index(['year', 'type']) #recreate the multilevel index
df
P Smith
  • 1
  • 2
  • Thanks for your answer. But this code changes the names of the indexes, i.e. year and type become year 0 and year 1. What I need is for 2017 to become Year 0 and 2018 to be Year 1 –  Jul 30 '19 at 08:08
0

You have do that indirectly, see here (by the way, this is a duplicate of other questions)

# remove 'year' and 'type' from index
df = df.reset_index()
# do changes to year
df.year = df.year.apply(lambda x: 'Year %i' %(x-2017))
# set 'year' and 'type'as indices
df = df.set_index(['year', 'type'])
user7440787
  • 831
  • 7
  • 22
  • @divakaivan could you please then add up vote the answer? Also, could you please clarify if the changes to the question are correct, i.e. if the expected result is right? – user7440787 Aug 01 '19 at 07:52
  • the exact code helped me and did what I said the question above –  Aug 01 '19 at 08:59