Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use first column after groupby?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

    df = df.groupby(['model']).mean().reset_index()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading