2016-10-13 6 views
2

に毎日データを変換する:は、私はこのようなdictsのリストを持って毎週手段と中央値

[ 
    {'2016-06-11': 10, 
    '2016-06-09': 10, 
    'ID': 1, 
    '2016-06-04': 10, 
    '2016-06-07': 10, 
    '2016-06-06': 10, 
    '2016-06-01': 10, 
    '2016-06-03': 10, 
    'type': 'primary', 
    '2016-06-05': 10, 
    '2016-06-10': 10, 
    '2016-06-02': 10, 
    '2016-06-08': 10}, 
    {'2016-06-11': 2, 
    '2016-06-09': 1, 
    'ID': 2, 
    'type': 'secondary', 
    '2016-06-04': 1, 
    '2016-06-07': 1, 
    '2016-06-06': 1, 
    '2016-06-01': 1, 
    '2016-06-03': 1, 
    '2016-06-05': 1, 
    '2016-06-10': 2, 
    '2016-06-02': 1, 
    '2016-06-08': 1} 
] 

私はキーが週間(月曜日から始まるだろうdictsの同様のリストにこれを変換する必要があり、したがって2016-06-03 - 2016-06-09)または月(たとえば、2016-06)であり、その値はその週/月の値の平均値または中央値のいずれかです。これを行う最も簡単な方法は何でしょうか?

答えて

1

は、私はあなたがmonthsによってresample、集計meanまたはmedianと最後DataFrame.to_dictによってdictlistを作成することができると思います。

df = pd.DataFrame(d) 
print (df) 
    2016-06-01 2016-06-02 2016-06-03 2016-06-04 2016-06-05 2016-06-06 \ 
0   10   10   10   10   10   10 
1   1   1   1   1   1   1 

    2016-06-07 2016-06-08 2016-06-09 2016-06-10 2016-06-11 ID  type 
0   10   10   10   10   10 1 primary 
1   1   1   1   2   2 2 secondary 

df.set_index(['type', 'ID'], inplace=True) 
df.columns = pd.to_datetime(df.columns) 
df = df.T.resample('M').mean() 
df.index = df.index.strftime('%Y-%m') 
print (df) 
type primary secondary 
ID   1   2 
2016-06 10.0 1.181818 

print (df.T.reset_index().to_dict(orient='records')) 
[{'type': 'primary', '2016-06': 10.0, 'ID': 1}, 
{'type': 'secondary', '2016-06': 1.1818181818181819, 'ID': 2}] 

df.set_index(['type', 'ID'], inplace=True) 
df.columns = pd.to_datetime(df.columns) 
df = df.T.resample('M').median() 
df.index = df.index.strftime('%Y-%m') 
print (df) 
type primary secondary 
ID   1   2 
2016-06  10   1 

print (df.T.reset_index().to_dict(orient='records')) 
[{'type': 'primary', '2016-06': 10, 'ID': 1}, 
{'type': 'secondary', '2016-06': 1, 'ID': 2}] 

別の解決策ではなく、reampleDatetimeIndex.to_periodによって作成された月の期間によってgroupbyです:

df = df.groupby([df.index.to_period('m')]).mean() 
df = df.groupby([df.index.to_period('m')]).median() 
+0

これは完璧です。今週は自分の週平均をどうやってやるかを考え出すことができます。ありがとう! – Nee

+0

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

関連する問題