2017-03-22 5 views
1

私は、Pythonを使用して大量のCSVデータを分析しています。このデータには、各行の最初のフィールドに示されているメトリックタイプを使用して、特定のタイムスタンプとホストペアの4種類のメトリックが含まれています。ここでは簡単な例です:だから使用する辞書を暗黙的に決定する

metric,timestamp,hostname,value 
metric1,1488063747,example01.net,12 
metric2,1488063747,example01.net,23 
metric3,1488063747,example01.net,34 
metric4,1488063747,example01.net,45 
metric1,1488063788,example02.net,56 
metric2,1488063788,example02.net,67 
metric3,1488063788,example02.net,78 
metric4,1488063788,example02.net,89 

、すべてのrowのために(リストのリスト内で、実際に、リスト)私は、タイムスタンプとホスト名で構成インデックスを作る:今すぐ

idx = row[1] + ',' + row[2] 

、上のベース最初のフィールド(リスト要素)の内容は、次のようになります。

if row[0] == 'metric1': metric_dict[idx] = row[3] 

私は4つの指標のそれぞれについてこれを行います。それは動作しますが、より良い方法があるはずです。私は何とか暗黙的または間接的にrow [0]の内容に基づいて使用する辞書を選択する必要があるようですが、私の検索で結果が得られていないようです。この場合、4 ifの行は厳しいものではありませんが、より多くのメトリックタイプがファイルに含まれることは珍しいことではありません。これを行うことは可能ですが、リストのリストを読んだあとに多くの辞書が必要ですが残しておきますか?ありがとうございました。

+2

をあなたは巣別の*辞書*のものdictsには、「'キーである' metrics'、言うことができますmetric1 "'であり、値は適切なdictです。したがって、 'metric [row [0]] [idx]'はあなたが使用することになります。 –

答えて

0

問題:十分なdicts。

ソリューション:

conversion_dict = {'metric1': metric1_dict, 'metric2': metric2_dict} 

for row: 
    conversion_dict[row[0]][idx] = row[3] 
0

あなたはテーブル操作の多くを

output = {} 
for row in rows: 
    # assuming this data is already split 

    if not row[0] in output: 
     output[row[0]] = {} 
    idx = row[1] + ',' + row[2] 
    output[row[0]][idx] = row[3] 
0

ような何かをやっているではない場合は、なぜ、あなたはpandasライブラリは参考になりましかもしれません。私はあなたが何をしようとして正しく理解していれば:

import pandas as pd 
from StringIO import StringIO 

s = StringIO("""metric,timestamp,hostname,value 
metric1,1488063747,example01.net,12 
metric2,1488063747,example01.net,23 
metric3,1488063747,example01.net,34 
metric4,1488063747,example01.net,45 
metric1,1488063788,example02.net,56 
metric2,1488063788,example02.net,67 
metric3,1488063788,example02.net,78 
metric4,1488063788,example02.net,89 
""") 

df = pd.read_csv(s) 
df.pivot(index="timestamp", columns='metric',values='value') 

この利回り:

metric  metric1 metric2 metric3 metric4 
timestamp          
1488063747  12  23  34  45 
1488063788  56  67  78  89 
関連する問題