0

I have a dataframe with a column multiindex and various data columns:

                 id value1 value2  valuen
name  date
foo   01-2000  No01    324   6575     ...
bar   02-2000  No02    964   0982     ...

Now I need to turn id into a number (df['id'] = df[id].str[1:]; df['id'] = df['id'].astype(int)) and add this as a third column to the multiindex.

Of course there's various ways to do that, but I'm wondering if there is one of the many, inbuilt pandas shortcuts for it, i.e. something like pd.make_index_col(df['id']) or df.add_to_index('id') to get a df with, in this case, 3 index columns:

                  value1 value2  valuen
name  date     id
foo   01-2000   1    324   6575     ...
bar   02-2000   2    964   0982     ...
2
  • 1
    df.set_index(df.pop("id").str[2:], append=True, inplace=True) ? Commented May 27, 2024 at 8:51
  • pop isn't exactly make_index_col or similar and the doc page isn't really helpful (and didn't turn up in my searches), but that works and is really straightforward. Can you post that as an answer? Unless someone jumps in and tells us why this is a bad idea, that seems like an acceptable answer to me. Commented May 27, 2024 at 8:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.