Skip to content Skip to sidebar Skip to footer

Python- Creating A Table

I am a python user in the very early stage. I have two data set of temperature over a specific location from the year 1850 to 2010 with one value of temperature for each month fo

Solution 1:

I would recommend that you have a look at string templates

Example:

>>>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'

If you create a string template of the target format and then place the data in a dictionary as described above, the conversion should be easy.

That is, if I interpreted your question correctly, i.e. you want to print a nice table to stdout...

Solution 2:

To print the above data in a table I would suggest a simple loop with some string formating:

print"\t".join(['year', 'data', 'Jan', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEZ'])
theYearOffset = 1850for 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]]))

This is not the most beautiful code possible but it will do the job. The columns are separated with tabulators and floating point numbers are roundet to 2 digits.

Here is the output for some stupid test data:

output

Test data:

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]

Post a Comment for "Python- Creating A Table"