2016-10-18 5 views
1

私は次のようにいくつかの時系列データをロードしています:パンダのインデックスの日付形式を変更するにはどうすればよいですか?

snp = web.DataReader("^GSPC", 'yahoo', start, end)['Adj Close'] 

インデックスは、自動的に「datetime64 [NS]」

としてフォーマットされて、私はその後、毎年、このように毎日データをリサンプリング:

snp_yr = snp.resample('A') 

日付の書式設定は、これまでと同じです。これを年だけに変更するにはどうすればいいですか(%Y)??

など。 '2015年12月31日夜12時〇〇分00秒' から '2015'

答えて

0

に私はあなたがDatetimeIndex.yearを必要とstringに変換が必要な場合、その後の追加と思うastype

df.index = df.index.year 

サンプル:

start = pd.to_datetime('2015-02-24') 
rng = pd.date_range(start, periods=10, freq='3M') 

df = pd.DataFrame({'a': range(10)},index=rng) 
print (df) 
      a 
2015-02-28 0 
2015-05-31 1 
2015-08-31 2 
2015-11-30 3 
2016-02-29 4 
2016-05-31 5 
2016-08-31 6 
2016-11-30 7 
2017-02-28 8 
2017-05-31 9 

df.index = df.index.year.astype(str) 
print (df) 
     a 
2015 0 
2015 1 
2015 2 
2015 3 
2016 4 
2016 5 
2016 6 
2016 7 
2017 8 
2017 9 

print (df.index) 
Index(['2015', '2015', '2015', '2015', '2016', '2016', '2016', '2016', '2017', 
     '2017'], 
     dtype='object') 

strftimeのもう一つの解決策:

df.index = df.index.strftime('%Y') 
print (df) 
     a 
2015 0 
2015 1 
2015 2 
2015 3 
2016 4 
2016 5 
2016 6 
2016 7 
2017 8 
2017 9 

print (df.index) 
Index(['2015', '2015', '2015', '2015', '2016', '2016', '2016', '2016', '2017', 
     '2017'], 
     dtype='object') 
+0

魅力的な作品、歓声。 – cJc

+0

うれしいことができますよ!いい日! – jezrael

関連する問題