Python-创建一个表

时间:2011-05-25 19:21:21

标签: python

我是早期阶段的python用户。

从1850年到2010年,我在特定地点有两个温度数据集,整个期间每个月有一个温度值。我试图用下面给出的格式创建一个包含这些值的表。 T是我的数据。

year data JAn FEB MAR APR MAY JUN JUL AUG SEP .......DEC.
1850 data1 t   t   t   t   t   t   t   t   t          t.
     data2 t   t   t   t   t   t   t   t   t          t.
'.
'.
'.
2010 data1 t   t   t   t   t   t   t   t  t           t.

对不起,我不能发布表格的图片我需要什么。我不允许发布图片。我无法指定我需要的桌子的形状。 所以我发布了另一个样本表的链接。 its another data set.但我需要在这一年中有两行。一个用于我的数据1,一个用于我的数据2.

现在我所拥有的是从1850年到2010年的完整的一系列数据。我想将上述给定格式的两个数据集重写为表格。从数据我每年切片data1和数据2。我知道这是一个通过办公室包很容易完成的工作,但我知道这不是编程的方式。请有人帮助我这样做。

这是我现在拥有的。

data1 = [t, t, t, t, t, t, t, t, t,..............................t]
data2 = [t, t, t, t, t, t, t, t, t,..............................t]

#This data1 and data2 is the list of data for the entire period from 1850-2010
#I sliced this data as
n = len(data1)
data1_yearly = [data1[i:i+12] for i in xrange(0,n,12)]
data2_yearly = [data2[i:i+12] for i in xrange(0,n,12)]

现在我有每年切片的data1和data2的值。 data1_yearly [0]给出了1850年数据的值,进一步索引将为我提供所有期间的数据。

所以从这里开始我的问题。 如何以上面指定的格式将此数据写为表格。我对这种语言完全是新手,所以请不要认为这个请求是愚蠢的,请善待我。

2 个答案:

答案 0 :(得分:2)

我建议您查看string templates

示例:

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
[...]
ValueError: Invalid placeholder in string: line 1, col 10
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
[...]
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'

如果您创建目标格式的字符串模板,然后将数据放入字典中,则转换应该很容易。

也就是说,如果我正确地解释了你的问题,即你想打印一个漂亮的表到stdout ......

答案 1 :(得分:1)

要在表格中打印上述数据,我建议使用一些字符串格式化的简单循环:

print "\t".join(['year', 'data', 'Jan', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEZ'])
theYearOffset = 1850
for theYearCounter in range(len(data1_yearly)):
    print "%s\t%s\t%s\n\t%s\t%s" % ((theYearOffset + theYearCounter), 
        'data1', "\t".join(["%.2f" % theValue for theValue in data1_yearly[theYearCounter]]), 
        'data2', "\t".join(["%.2f" % theValue for theValue in data2_yearly[theYearCounter]]))

这不是最美丽的代码,但它可以完成这项工作。列用制表符分隔,浮点数为2位数。

以下是一些愚蠢的测试数据的输出:

output

测试数据:

data1 = [1.1233,2,3,4,5,6,7,8,9,10,11,1,2,3,4,5,6,7,8,9,10,11,1,2,3,4,5,6,7,8,9,10,11,1,2,3,4,5,6,7,8,9,10,11]
data2 = [8,9,10,11,12,13,14,15,1,2,4,8,9,10,11,12,13,14,15,1,2,4,8,9,10,11,12,13,14,15,1,2,4,8,9,10,11,12,13,14,15,1,2,4]