Reputation: 127
I'm sure this has been asked before but I can't find the correct way to go about doing this. I have a dataframe with a datetime index
df = col2
test
| 04-05-2018 | 56 |
| 04-06-2018 | 23 |
| 04-07-2018 | 87 |
| 04-08-2018 | 11 |
What I would like to do is to access (and consequently create a new column from) the month property of the datetime index. I have tried to just access the property using print(df['test'].datetime.month)
but I receive the expected KeyError (I know that the title of the dataframe is 'test' and not the index itself, I just don't know what to do).
Any help is greatly appreciated, and thanks in advance.
Upvotes: 0
Views: 2833
Reputation: 65
import pandas as pd
data = [['04-05-2018',56] ,
['04-06-2018',23],
['04-07-2018',87],
['04-08-2018',11]]
df = pd.DataFrame(data, columns =['test', 'col2'])
df.set_index('test', inplace=True)
df
col2
test
04-05-2018 56
04-06-2018 23
04-07-2018 87
04-08-2018 11
df=dfT.reset_index()
df['Months'] = list(dfT['test'].astype(str).str[3:5])
df
col2 Months
test
04-05-2018 56 05
04-06-2018 23 06
04-07-2018 87 07
04-08-2018 11 08
Done ✅✅
Upvotes: 1
Reputation: 1126
Like this?
import pandas as pd
ind = ['04-05-2018','04-06-2018', '04-07-2018', '04-08-2018']
col2 = [56,23,87,11]
df = pd.DataFrame(col2, index = ind, columns = ['col2'])
Out[1]:
col2
04-05-2018 56
04-06-2018 23
04-07-2018 87
04-08-2018 11
df['month'] = pd.to_datetime(df.index).month
df
Out[2]:
col2 month
04-05-2018 56 4
04-06-2018 23 4
04-07-2018 87 4
04-08-2018 11 4
df['month_s'] = [str(mnth).zfill(2) for mnth in pd.to_datetime(df.index).month]
df
Out[3]:
col2 month month_s
04-05-2018 56 4 04
04-06-2018 23 4 04
11-07-2018 87 4 04
04-08-2018 11 4 04
Upvotes: 0
Reputation: 515
Hope this is what you're looking for:
import pandas as pd
data = [['04-05-2018',56] ,
['04-06-2018',23],
['04-07-2018',87],
['04-08-2018',11]]
df = pd.DataFrame(data, columns =['test', 'col2'])
df.set_index('test', inplace=True)
df['MONTH'] = pd.to_datetime(df.index).month
df
col2 Month
test
04-05-2018 56 4
04-06-2018 23 4
04-07-2018 87 4
04-08-2018 11 4
Upvotes: 1