0

I am trying to extract the numerical month from the DataFrames index column (these are currently in my DateTime objects).

The step before I Used the resample function followed by the sum function to calculate the total usage for each month. Store this in a variable called monthly.

Date                                    
2012-01-31  4915    
2012-02-29  6712    
2012-03-31  26229   
2012-04-30  67699   

To extract the numerical month from the DataFrames index column ive tried

monthly['Month'] = pd.DatetimeIndex(monthly['Date']).month  

but I get an error keyError:'Date'

Mine
  • 1
  • 1
  • Welcome to Stack Overflow! I appreciate how you explained how you got to your dataframe, but it would make it even easier to assist if you can provide a way to reconstruct your dataframe. For example: > monthly = pd.Series([4915, 6712], index=pd.DatetimeIndex([date(2012,1,31), date(2012,2,29)], name='Date')) > monthly Date 2012-01-31 4915 2012-02-29 6712 dtype: int64 – Matthew Cox Jan 20 '23 at 20:31
  • Does this answer your question? [Extracting just Month and Year separately from Pandas Datetime column](https://stackoverflow.com/questions/25146121/extracting-just-month-and-year-separately-from-pandas-datetime-column) – Anoushiravan R Jan 20 '23 at 21:16
  • I tried doing that, but unfortunately, it did not help. – Mine Jan 20 '23 at 21:57

1 Answers1

0

Assuming that you have a series looks like this:

> monthly = pd.Series([4915, 6712], index=pd.DatetimeIndex([date(2012,1,31), date(2012,2,29)], name='Date'))
> monthly
Date
2012-01-31    4915
2012-02-29    6712
dtype: int64

I assume that you want a new column, so you should first turn the series into a dataframe:

> monthly_df = pd.DataFrame({'values': monthly})

Then can reference the index directly. For example:

> monthly_df['Month'] = monthly.index.month
> monthly_df
              values  Month
Date                     
2012-01-31    4915      1
2012-02-29    6712      2
Matthew Cox
  • 1,047
  • 10
  • 23