[Tutor] Create a pivot table

Peter Otten __peter__ at web.de
Fri May 20 08:41:28 EDT 2016


jarod_v6--- via Tutor wrote:

Please address your posts to the whole list, not me specifically. I might 
read them all the same. 

Thank you.

> Thanks s much for  the help. I want to obtain table like this:
> 
> 
>>csv.writer(sys.stdout, delimiter="\t").writerows(table)
>>        A100    D33     D34     D35     D36     D37     D38     D39
>>A       5         0 ...
>>B       2         2  ...
>>C      0  ..
>>
> I have tried the pandas way but unfortunately there is many duplicates .

Please show your code in a small self-contained example, 
the output it produces, and what exact output you want instead.
Then one of us (not necessarily me) might be able to help you fix it.

> So
> Now I move to create a new file using dictionary  and  a file with this
> format.
> 
> ('A', A100') 5
> ('B', 'A100) 2
> 
> I just wondering if there is a pythonic way to do this. 

"Pythonic" is elegant idiomatic Python. At this stage I'd settle for 
anything that works. Just saying...

> I don't want to use another software if I can

$ cat pivot_demo2.py
import csv
import operator
import sys
from pivot import pivot

data = {
    ("A", "A100"): 5,
    ("B", "A100"): 2,
    ("B", "D33"): 2,
}

table = pivot(
    data,
    operator.itemgetter(1),
    operator.itemgetter(0),
    lambda k, data=data: data[k],
    empty=0)
csv.writer(sys.stdout, delimiter="\t").writerows(table)
$ python3 pivot_demo2.py
        A100    D33
A       5       0
B       2       2
$ 




More information about the Tutor mailing list