Home > Enterprise >  Use first column after groupby?
Use first column after groupby?

Time:12-02

I have a pd Dataframe df with a column 'model' which I used for a groupby:

df = df.groupby(['model']).mean()

Now, I want to perform a lambda operation on the resulting df:

df['num_topics'] = df['model'].apply(lambda x: x.split('-')[1])

However, when I run this, I get the following error:

Traceback (most recent call last):

  File "<ipython-input-898-2f5c4b35d5ba>", line 1, in <module>
    df = full_df.create_effect_num_topics()

  File "<ipython-input-896-6ace6e90c7d0>", line 28, in create_effect_num_topics
    df['num_topics'] = df['model'].apply(lambda x: x.split('-')[1])

  File "C:\Users\20200016\Anaconda3\lib\site-packages\pandas\core\frame.py", line 3458, in __getitem__
    indexer = self.columns.get_loc(key)

  File "C:\Users\20200016\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3363, in get_loc
    raise KeyError(key) from err

KeyError: 'model'

It seems that model is the index now and not an editable cell anymore. How can I make it a regular column again, so that I can use it for lambda expressions?

CodePudding user response:

you can use this to reset index/level in a dataframe

    df = df.groupby(['model']).mean().reset_index()
  • Related