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.
抱歉,我不能发表格的图片,因为不允许这样做。而且我也无法准确描述我想要的表格形状。所以我发了一个链接,里面有另一个样本表格。这是另一个数据集。 但我需要在年份旁边有两行,一行是我的数据1,另一行是我的数据2。
现在我有了从1850年到2010年的完整数据系列。我想把这两个数据集按照上面给出的格式重新整理成一个表格。从我已有的数据中,我已经为每一年提取了数据1和数据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)]
现在我已经为每一年提取了数据1和数据2的值。data1_yearly[0]给我的是1850年的数据,继续索引就能得到整个时期的数据。
所以我的问题就从这里开始了。我该如何把这些数据写成我上面指定格式的表格呢?我对这门语言完全是新手,所以请不要把这个请求当成愚蠢的要求,恳请大家帮帮我。
2 个回答
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]]))
这段代码可能不是最完美的,但它能完成任务。列与列之间用制表符分隔,浮点数会四舍五入到小数点后两位。
下面是一些简单测试数据的输出结果:
测试数据:
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]
2
我建议你看看字符串模板
举个例子:
>>> 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'
如果你创建一个目标格式的字符串模板,然后像上面说的那样把数据放进一个字典里,转换应该会很简单。
也就是说,如果我理解你的问题没错的话,你是想把一个漂亮的表格打印到标准输出上……