2017-02-13 19 views
0

私は、辞書の3次元辞書として格納されているいくつかのメトリックを計算するコードを持っています。私はcsvファイルにこの辞書を印刷したいと思いますが、そうすることで良い方法は見つけられていません。多次元辞書をファイルに書き込む

一旦辞書内のすべての要素が計算され、Iは、( - 列キーとカラムメトリック異なるperiodsが列でなければならないファイルのヘッダおよびkeysと指標a, b, and cである)、それがファイルに印刷したいです。

これをファイルに簡単に印刷する方法はありますか? (私の最初の試みはパンダだったが、これは動作しませんでした)

ありがとうございますが、これだけのためにcsvモジュールを使用する必要があります

from collections import defaultdict 
import pandas as pd 
import os 
import random 


# 3 dimensional dictionary that stores integers 
output_dict = defaultdict(lambda: defaultdict(lambda: defaultdict(int))) 
# Array of periods 
periods = range(0, 2) 
# relevant keys 
keys = ["key1", "key2"] 

# Iterate over all periods 
for period in periods: 
    # Iterate over all relevant keys 
    for key in keys: 

     # Store results for key for each time period for each category ("a", "b", or "c") 
     output_dict[key][period]["a"] += random.randint(1, 1000) 
     output_dict[key][period]["b"] += random.randint(1, 1000) 
     output_dict[key][period]["c"] += random.randint(1, 1000) 

# This is the tricky part!!! 
# Store results 
pd.DataFrame(output_dict).to_csv("output_dict.csv", index=False) 

# the dictionary may look as follows: 
output_dict = {"key1": {0: {"a": 0.9, "b": 0.2, "c": 0.5}, 1:{"a": 0.91, "b": 0.3, "c": 0.4}}, 
       "key2": {0: {"a": 0.4, "b": 0.33, "c": 0.34}, 1: {"a": 0.21, "b": 0.73, "c": 0.54}}} 

enter image description here

+1

まず、とパンダのデータフレームにデータを変換してみてください'key'、' a'、 'b'、' c'の列。それから、CSVへの投棄はかなり苦痛であるはずです。 –

+1

あなたの辞書がどのように見えるか、そしてCSVをどのように見せたいかを例えれば助けになるでしょう。 –

+0

@JackManey:パンダには簡単な方法がありますか?おそらく@Andreas – Andreas

答えて

1

を、私はそれがあなたのデータを論争する価値はないと思いますpandas DataFrameコンストラクタでうまく再生できるようにしてください。私は結果を簡単に印刷することができるように、ファイルの代わりに文字列のI/Oバッファにcsvを書いていますが、単純にその内容を省略して通常のファイルオブジェクトで作業することができます。

>>> periods = [0, 1] 
>>> metrics = ['a', 'b', 'c'] 
>>> import csv 
>>> import io 

今、ちょうど慎重に行を構築:辞書は順不同であるため、

>>> with io.StringIO() as f: 
...  writer = csv.writer(f) 
...  writer.writerow(['Key','Metric', 0, 1]) 
...  for key in output_dict: 
...   for metric in metrics: 
...    row = [key, metric] 
...    for p in periods: 
...     row.append(output_dict[key][p][metric]) 
...    writer.writerow(row) 
...  final = f.getvalue() 
... 
16 
17 
18 
18 
17 
16 
16 
>>> print(final) 
Key,Metric,0,1 
key2,a,0.4,0.21 
key2,b,0.33,0.73 
key2,c,0.34,0.54 
key1,a,0.9,0.91 
key1,b,0.2,0.3 
key1,c,0.5,0.4 

注意を、キーが特定の順序ではありません。私がメトリクスや期間で行ったように、事前に知っていればすべてのキーを繰り返し処理することで注文を行うことができます(は事前にとなっています)。この解決法は、失われた鍵をかなり簡単に処理するために拡張することができます。

EDITは: あなたの最後の編集はこれだけのような何かを、あなたは事前に鍵を知っているだろうことを意味するようだ:

>>> periods = [0, 1] 
>>> keys = ['key1', 'key2'] 
>>> metrics = ['a', 'b', 'c'] 
>>> with io.StringIO() as f: 
...  writer = csv.writer(f) 
...  writer.writerow(['Key','Metric', 0, 1]) 
...  for key in keys: 
...   for metric in metrics: 
...    row = [key, metric] 
...    for p in periods: 
...     row.append(output_dict[key][p][metric]) 
...    writer.writerow(row) 
...  final = f.getvalue() 
... 
16 
17 
16 
16 
17 
18 
18 
>>> print(final) 
Key,Metric,0,1 
key1,a,0.9,0.91 
key1,b,0.2,0.3 
key1,c,0.5,0.4 
key2,a,0.4,0.21 
key2,b,0.33,0.73 
key2,c,0.34,0.54 
+0

ありがとうございます。これはまさに私が探していたものです! あなたの投稿に関する2つの質問: a)csvファイルに 'final'をどのように書きますか? b) "writerow"機能を動的にする簡単な方法があります(例えば、無制限の期間がある) – Andreas

関連する問題