1

I am fairly new to Python, I am trying to convert the Series coming out from groupby() into a dataframe, that I will merge to the main df. However, to_frame() seems not working as it keeps returning a series not a dataframe.Any help will be greatly appreciated See following code:

IN: pf_avg = df.groupby('release_year').profit.mean() 
    pf_avg.to_frame()
    type(pf_avg)

OUT: pandas.core.series.Series

IN: df_pf_avg = df.merge(pf_avg, left_on= 'release_year', right_index= True)
    df_pf_avg.head()

OUT: ValueError: can not merge DataFrame with instance of type <class 
    'pandas.core.series.Series'>
mauve
  • 2,707
  • 1
  • 20
  • 34
Simone Di Claudio
  • 131
  • 1
  • 2
  • 8
  • 2
    First of all, `to_frame()` *returns a new object which is a data frame*. It does not *change* the object that called the method. So you should do `pf_avg = pf_avg.to_frame()` to see the difference. In addition, you likely want just `df['new_column'] = df.groupby('release_year').profit.transform('mean')` – rafaelc Apr 05 '19 at 19:59
  • 2
    From v0.24, you _don't_ need to convert from series to dataframe. Pass it to df.merge directly. See [this answer](https://stackoverflow.com/a/40762674/4909087) – cs95 Apr 05 '19 at 20:00
  • thank you very much, I don't know how to reward you guys if this is a possibility. – Simone Di Claudio Apr 07 '19 at 14:16

0 Answers0