Reputation: 21
I have a simple pandas dataframe with a date as index:
import pandas as pd
data = {'date': ['2010-01-04','2014-03-15','2017-07-15','2019-12-28','2005-01-03'],
'price': [1095.20,1139.15,1126.15,1138.00,1125.80]
}
df = pd.DataFrame(data, columns = ['date', 'price'])
df['date']= pd.to_datetime(df['date'])
df = df.set_index('date')
I can add columns with year, weekday and week:
df['year'] = df.index.year
df['dayofweek'] = df.index.weekday
df['week'] = df.index.week
But I found:
pandas.DatetimeIndex.week
Deprecated since version 1.1.0. weekofyear and week have been deprecated. Please use DatetimeIndex.isocalendar().week instead.
This doesn't work
df['isoweek'] = df.index.isocalendar().week
--> AttributeError: 'DatetimeIndex' object has no attribute 'isocalendar'
This doesn't work either:
df['isoweek'] = ""
for i in df.index:
df.loc[i].isoweek = i.isocalendar()[1]
This does, but still gives me a warning:
for i in df.index:
df.loc[:, ('isoweek')][i] = i.isocalendar()[1]
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
There is probably a very simple solution for this, but I can't find it...
Upvotes: 2
Views: 1558
Reputation: 370
I ended up doing this:
df_tmp['week'] = df_tmp.index.map(lambda v: pd.to_datetime(v).isocalendar()[1])
Upvotes: 1