2014-10-21 103 views
0

我有這樣的數據:如何將pandas數據框中的DateTimeIndex更改爲同一年?

    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 

如何重新索引的數據(observation_date),使所有的幾年成爲2013?

因此,1970-01-31變成了2013-01-31等等。我知道索引將會有很多次相同。

回答

2
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) 

產生

   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 
+0

這正是我想要的。謝謝。 – jenny 2014-10-21 22:45:56

+0

@ user3914487在這種情況下,您應該接受答案作爲有效答案。 – user3378649 2014-10-22 09:36:45

+0

我已經這樣做了。謝謝user3378649和unutbu。 – jenny 2014-10-22 15:57:01

0

我會寫更新一年的函數。 我會在這裏通過一個簡單的例子。

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 

輸出::

observation_date   b 
0  1970-01-31 2013-01-31 
1  1970-02-31 2013-02-31 
2  1970-04-31 2013-04-31 

你的情況:

df= pd.read_csv(name) 
df.index = df.index.apply(lambda x:updateYear(str(x))) 
-1

不知道如果我理解你的問題,但你可以搜索年startswith 1970年和2013與

更換

例如。

NEW_DATE =應用re.sub( '1970年', '2013',observation_date)

相關問題