TerrifiedJelly
TerrifiedJelly

Reputation: 135

Adding column header to series

I'm new to Python and I'm trying to get my series in to a dataframe and rename the headers to Month and Minutes.

Below I'm grouping the data in to 'df'

df = data
df = df.groupby(df['endTime'].dt.strftime('%Y-%m'))['Minutes'].sum().sort_index()
print(df)

Output of the above code

Then I'm transforming the series in to a dataframe

df1 = pd.DataFrame(df)
print(df1)

At this point the column header starts being on a different level as if they're on separate rows enter image description here

I can't work out how to then correct this or change the column names in any other way. I'm using Jupyter Notebook

             Minutes
endTime             
2019-10   516.386967
2019-11  4423.741683
2019-12  5508.101017
2020-01  3802.073583
2020-02  3790.562850
2020-03  3260.039417
2020-04  1913.841267
2020-05  1554.578183
2020-06  2094.596467
2020-07  3061.289633
2020-08  1676.243450
2020-09  4790.751267
2020-10  6404.273800

Upvotes: 0

Views: 273

Answers (3)

Vivek Kalyanarangan
Vivek Kalyanarangan

Reputation: 9081

Try -

df.groupby(df['endTime'].dt.strftime('%Y-%m'))['Minutes'].sum().reset_index()

Upvotes: 1

Aaj Kaal
Aaj Kaal

Reputation: 1304

All you need is

df.reset_index(level=0, inplace=True)

Upvotes: 1

mlang
mlang

Reputation: 762

The endTime column is the index of the DataFrame after running groupby. This explains why it is displayed separately. If you want to get the endTime back as regular column in the DataFrame, you can just run the following command:

df.reset_index(inplace=True)

Upvotes: 1

Related Questions