Reputation: 811
I have data like this:
Charge 1 Charge 2
observation_date
1970-01-31 35.535318 0.073390
1970-02-28 27.685739 0.050302
...
2013-01-31 27.671290 0.296882
2013-02-28 26.647262 0.225714
2013-03-31 21.495699 0.362151
How do I re-index the data (the observation_date) so that all the years become 2013?
So 1970-01-31 becomes 2013-01-31, etc. I understand that there will be many times when the index will be the same.
Upvotes: 1
Views: 5030
Reputation: 1
not sure if I understand your question, but you can search for year startswith 1970 and replace with 2013
eg.
new_date = re.sub('1970', '2013', observation_date)
Upvotes: -1
Reputation: 5354
I will write a function that update the year. I will go through a quick example here.
import pandas as pd
df = pd.DataFrame({'observation_date':["1970-01-31","1970-02-31","1970-04-31"]})
l= df.observation_date
def updateYear(x):
n= x.split("-")
n[0]="2013" #We replace the year data, which is the first value by 2013
return "-".join(n)
print updateYear("1970-01-31")
df['b']= df["observation_date"].apply(lambda x:updateYear(str(x)))
print df
Output::
observation_date b
0 1970-01-31 2013-01-31
1 1970-02-31 2013-02-31
2 1970-04-31 2013-04-31
In your case:
df= pd.read_csv(name)
df.index = df.index.apply(lambda x:updateYear(str(x)))
Upvotes: 0
Reputation: 879251
import pandas as pd
df = pd.read_table('data', sep='\s{2,}').set_index('observation_date')
df.index = pd.DatetimeIndex(df.index)
df.index = df.index + pd.DateOffset(year=2013)
print(df)
yields
Charge 1 Charge 2
2013-01-31 35.535318 0.073390
2013-02-28 27.685739 0.050302
2013-01-31 27.671290 0.296882
2013-02-28 26.647262 0.225714
2013-03-31 21.495699 0.362151
Upvotes: 4