2017-10-19 10 views
0

データセットで機械学習を行うためにデータクリーニングを行っています。 基本的に私は過去12ヶ月に基づいて次の12ヶ月の値を予測したいと思います。 私は1ヶ月あたりの価値を持つデータセットを持っています(下記の例)。Python/Pandasでデータをクリーニングして月の組み合わせを繰り返す

私は12ヶ月の可能な組み合わせごとに繰り返しモデルを訓練したいと思います。 たとえば、2014-01から2014-12に2015-01から2015-12に移住し、2014-02から2015-01に2015-02から2016-01に移住するように彼を養成したいと考えています。

しかし、私はこれらの可能性をすべて満たすために苦労しています。 私は現在私のコードのどこにいるのか、私が望むものの下の例(12の代わりにわずか6ヶ月)を示します。

import pandas as pd 
import numpy as np 

data = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]] 
Months=['201401','201402','201403','201404','201405','201406','201407','201408','201409','201410','201411','201412','201501','201502','201503','201504','201505','201506','201507','201508','201509','201510','201511','201512'] 
df = pd.DataFrame(data,columns=Months) 

私が働くことができない部分。

X = np.array([]) 
Y = np.array([]) 

for month in Months: 
    loc = df.columns.get_loc(month) 
    print(month,loc) 
    if loc + 11 <= df.shape[1]: 
     X = np.append(X,df.iloc[:,loc:loc+5].values,axis=0) 
     Y = np.append(Y,df.iloc[:,loc+6:loc+1].values,axis=0) 

これは私が日付のあなたの説明で説明しているような範囲(というよりも、あなたのサンプル出力に示されているもの)を生成するには(最初の3 iteratios用)

### RESULTS EXPECTED #### 
X = [[1,2,3,4,5,6],[2,3,4,5,6,7],[3,4,5,6,7,8]] 
Y = [[7,8,9,10,11,12],[8,9,10,11,12,13],[9,10,11,12,13,14]] 

答えて

1

を期待していものですあなたは次のようなパンダの機能を使うことができます:

import pandas as pd 

months = pd.Series([ 
'201401','201402','201403','201404','201405','201406', 
'201407','201408','201409','201410','201411','201412', 
'201501','201502','201503','201504','201505','201506', 
'201507','201508','201509','201510','201511','201512' 
]) 

# this function converts strings like "201401" 
# to datetime objects, and then uses DateOffset 
# and date_range to generate a sequence of months 
def date_range(month): 
    date = pd.to_datetime(month, format="%Y%m") 
    return pd.date_range(date, date + pd.DateOffset(months=11), freq='MS') 

# apply function to original Series 
# and then apply pd.Series to expand resulting arrays 
# into DataFrame columns 
month_ranges = months.apply(date_range).apply(pd.Series) 

# sample of output: 
#   0   1   2   3   4   5 \ 
# 0 2014-01-01 2014-02-01 2014-03-01 2014-04-01 2014-05-01 2014-06-01 
# 1 2014-02-01 2014-03-01 2014-04-01 2014-05-01 2014-06-01 2014-07-01 
# 2 2014-03-01 2014-04-01 2014-05-01 2014-06-01 2014-07-01 2014-08-01 
# 3 2014-04-01 2014-05-01 2014-06-01 2014-07-01 2014-08-01 2014-09-01 
+0

また、データの場合、範囲を生成することもできます:list(range(1,25)) – skrubber

関連する問題