隐含地决定应该使用哪本字典

2024-06-28 14:52:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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个指标中的每一个都这样做。这是可行的,但似乎应该有更好的办法。似乎我需要根据第[0]行的内容以某种方式隐式或间接地选择要使用的词典,但我的搜索没有产生结果。在本例中,4if行并不难,但是在一个文件中包含更多的度量类型并不罕见。有没有可能做到这一点,并在阅读列表后留下多少词典?多谢各位


Tags: 数据类型列表net度量时间metricrow
3条回答

问题:没有足够的口述

解决方案:

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

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

为什么不像这样

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]

如果您正在进行大量的表操作,您可能会发现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

相关问题 更多 >