1

I have created a dataframe called date as follows, but I am not able to call that dataframe by typing date in further cells. I need to call that dataframe as a table and add new column to it.

Right now, this is what I have:

date = data.groupby(pd.to_datetime(data['Completion Date'], format='%d.%m.%Y').dt.month)['Learning    Hours'].sum()
date.index = pd.to_datetime(date.index, format='%m').month_name().str[:3]
date.rename_axis('Month').reset_index(name='Learning hours')

O/P:

Month   Learning hours

Jan     349.5

Feb     417.0

I need to add a new column to this table called Required, with values 430 in all rows as shown in the below:

needed O/P:

Month   Learning hours  Required

Jan     349.5           430

Feb     417.0           430
1
  • Added codeblocks to make output and code more readable Commented Apr 25, 2020 at 15:18

1 Answer 1

2

I think here is necessary assign output back to date variable and then create new colum:

date = data.groupby(pd.to_datetime(data['Completion Date'], format='%d.%m.%Y').dt.month)['Learning Hours'].sum() 
date.index = pd.to_datetime(date.index, format='%m').month_name().str[:3] 
date = date.rename_axis('Month').reset_index(name='Learning hours')
date['Required'] = 430

You can simplify solution if possible lowercases first 3 letters of months names:

months = (pd.to_datetime(data['Completion Date'], format='%d.%m.%Y')
            .dt.strftime('%b')
            .rename('Month'))
date = (data.groupby(months, sort=False)['Learning Hours']
            .sum()
            .reset_index(name='Learning hours'))
date['Required'] = 430

Or:

months = (pd.to_datetime(data['Completion Date'], format='%d.%m.%Y')
            .dt.strftime('%b')
            .rename('Month'))
date = (data.groupby(months, sort=False)['Learning Hours']
            .sum()
            .reset_index(name='Learning hours')
            .assign(Required = 430))
Sign up to request clarification or add additional context in comments.

4 Comments

But how to print Jan, Feb in that order. Your code is printing Feb first.
@VishvamNaik - How working data.groupby(months, sort=False) ?
It is working for all the months except Mar, Apr. I don't know what's the issue there. @jezrael
@VPN If data are not confidental is possible share them?

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.