[Tutor] Create a pivot table
Peter Otten
__peter__ at web.de
Thu May 19 13:19:24 EDT 2016
jarod_v6--- via Tutor wrote:
> Dear All!
> This is my data from a file. I want to obtain a count table how many
> times c11 are present for each project and Samples and Program.
>
> ['Program', 'Sample', 'Featurename', 'Project'],
> ['A', 'A100', 'c11', 'post50'],
> ['A', 'A100', 'c12', 'post50'],
> ['A', 'A100', 'c14', 'post50'],
> ['A', 'A100', 'c67', 'post50'],
> ['A', 'A100', 'c76', 'post50'],
> ['B', 'A100', 'c11', 'post50'],
> ['B', 'A100', 'c99', 'post50'],
> ['B', 'D33', 'c33', 'post50'],
> ['B', 'D33', 'c31', 'post50'],
> ['C', 'D34', 'c32', 'post60'],
> ['C', 'D35', 'c33', 'post60'],
> ['C', 'D36', 'c11', 'post60'],
> ['C', 'D37', 'c45', 'post60'],
> ['C', 'D38', 'c36', 'post60'],
> ['C', 'D39', 'c37', 'post60']
> I want to obtain pivot table with samples on columns and program as rown
> and the values I want fusionwhat it is the best way to do this?thanks in
> advance!
With the pivot() function from
https://mail.python.org/pipermail/tutor/2016-April/108671.html
>>> rows = [
... ['A', 'A100', 'c11', 'post50'],
... ['A', 'A100', 'c12', 'post50'],
... ['A', 'A100', 'c14', 'post50'],
... ['A', 'A100', 'c67', 'post50'],
... ['A', 'A100', 'c76', 'post50'],
... ['B', 'A100', 'c11', 'post50'],
... ['B', 'A100', 'c99', 'post50'],
... ['B', 'D33', 'c33', 'post50'],
... ['B', 'D33', 'c31', 'post50'],
... ['C', 'D34', 'c32', 'post60'],
... ['C', 'D35', 'c33', 'post60'],
... ['C', 'D36', 'c11', 'post60'],
... ['C', 'D37', 'c45', 'post60'],
... ['C', 'D38', 'c36', 'post60'],
... ['C', 'D39', 'c37', 'post60']
... ]
>>> table = pivot(rows, operator.itemgetter(1), operator.itemgetter(0),
lambda r: r[2] == "c11")
>>> csv.writer(sys.stdout, delimiter="\t").writerows(table)
A100 D33 D34 D35 D36 D37 D38 D39
A 1 -/- -/- -/- -/- -/- -/- -/-
B 1 0 -/- -/- -/- -/- -/- -/-
C -/- -/- 0 0 1 0 0 0
There are probably many other options, but you should seriously consider
using a spreadsheet application.
More information about the Tutor
mailing list