473,225 Members | 1,375 Online

# Pivot Table/Groupby/Sum question

Hi all,

on the same subject, but it didn't work for me. I'm trying to learn
how to make pivot tables from some excel sheets and I am trying to
abstract this into a simple sort of example. Essentially I want to
take input data like this:

Name Time of day Amount
Bob Morn 240
Bob Aft 300
Joe Morn 70
Joe Aft 80
Jil Morn 100
Jil Aft 150

And output it as:

Name Total Morning Afternoon
Bob 540 240 300
Joe 150 70 80
Jil 250 100 150
Total 940 410 530

The writing the output part is the easy part. However, I have a
couple problems. 1) Grouping by name seems to work perfectly, but
working by time does not. ie

I will get:
Bob
240
300
Joe
70
80
Jil
100
150
which is great but...
Morn
240
Aft
300
Morn
70
Aft
80
Morn
100
Aft
150
And not
Morn
240
70
100
Aft
300
80
150

2) I can't figure out how to sum these values because of the
iteration. I always get an error like: TypeError: iteration over non-
sequence

Here's the code:

from itertools import groupby

data = [['Bob', 'Morn', 240],['Bob', 'Aft', 300],['Joe', 'Morn', 70],
['Joe', 'Aft', 80],\
['Jil', 'Morn', 100],['Jil', 'Aft', 150]]

NAME, TIME, AMOUNT=range(3)
for k, g in groupby(data, key=lambda r: r[NAME]):
print k
for record in g:
print "\t", record[AMOUNT]
for k, g in groupby(data, key=lambda r: r[TIME]):
print k
for record in g:
print "\t", record[AMOUNT]

Dec 27 '07 #1
9 2963
What about to let SQL to work for you.
HTH

Petr Jakes

Tested on Python 2.5.1
8<----------------------

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()

inputData=(
('Bob', 'Morn', 240),
('Bob', 'Aft', 300),
('Joe', 'Morn', 70),
('Joe', 'Aft', 80),
('Jil', 'Morn', 100),
('Jil', 'Aft', 150),
('Jil', 'Aft', 150),
('Jil', 'Aft', 150))

def data_generator(dataSet):
for dataSetRow in dataSet:
yield dataSetRow

pivotSelect='''
SELECT
NAME,
sum (AMOUNT) as TOTAL,
sum (case when (TIME_OF_DAY) = 'Morn' then AMOUNT else 0 END) as
MORN,
sum (case when (TIME_OF_DAY) = 'Aft' then AMOUNT else 0 END) as AFT
FROM MY_NAMES
GROUP BY 1'''

cur.execute("create table MY_NAMES(NAME, TIME_OF_DAY, AMOUNT)")
cur.executemany("""insert into MY_NAMES(NAME, TIME_OF_DAY, AMOUNT)
values (?,?,?)""", data_generator(inputData))
cur.execute(pivotSelect)
for row in cur.fetchall():
print row
Dec 28 '07 #2
On Dec 29, 9:58 am, petr.jakes....@gmail.com wrote:
What about to let SQL to work for you.
The OP is "trying to learn how to make pivot tables from some excel
sheets". You had better give him a clue on how to use ODBC on an
"excel sheet" :-)

[snip]
SELECT
NAME,
sum (AMOUNT) as TOTAL,
sum (case when (TIME_OF_DAY) = 'Morn' then AMOUNT else 0 END) as
MORN,
sum (case when (TIME_OF_DAY) = 'Aft' then AMOUNT else 0 END) as AFT
This technique requires advance knowledge of what the column key
values are (the hard-coded 'Morn' and 'Aft').

<rant>
It is the sort of thing that one sees when %SQL% is the *only*
language used to produce end-user reports. Innocuous when there are
only 2 possible columns, but bletchworthy when there are more than 20
and the conditions are complex and the whole thing is replicated
several times in the %SQL% script because either %SQL% doesn't support
temporary procedures/functions or the BOsFH won't permit their use...
not in front of the newbies, please!
</rant>
Dec 29 '07 #3
Petr, thanks for the SQL suggestion, but I'm having enough trouble in
Python.

John would you mind walking me through your class in normal speak? I
only have a vague idea of why it works and this would help me a lot to
get a grip on classes and this sort of particular problem. The next
step is to imagine if there was another variable, like departments and
add up the information by name, department, and time, and so on...that
will come another day.

Thanks.

On Dec 29, 1:00 am, John Machin <sjmac...@lexicon.netwrote:
On Dec 29, 9:58 am, petr.jakes....@gmail.com wrote:
What about to let SQL to work for you.

The OP is "trying to learn how to make pivot tables from some excel
sheets". You had better give him a clue on how to use ODBC on an
"excel sheet" :-)

[snip]
SELECT
NAME,
sum (AMOUNT) as TOTAL,
sum (case when (TIME_OF_DAY) = 'Morn' then AMOUNT else 0 END) as
MORN,
sum (case when (TIME_OF_DAY) = 'Aft' then AMOUNT else 0 END) as AFT

This technique requires advance knowledge of what the column key
values are (the hard-coded 'Morn' and 'Aft').

<rant>
It is the sort of thing that one sees when %SQL% is the *only*
language used to produce end-user reports. Innocuous when there are
only 2 possible columns, but bletchworthy when there are more than 20
and the conditions are complex and the whole thing is replicated
several times in the %SQL% script because either %SQL% doesn't support
temporary procedures/functions or the BOsFH won't permit their use...
not in front of the newbies, please!
</rant>
Dec 29 '07 #4
On Dec 29, 11:51 am, patrick.wa...@gmail.com wrote:
John would you mind walking me through your class in normal speak?
Yes.
I
only have a vague idea of why it works and this would help me a lot to
get a grip on classes and this sort of particular problem.
It's about time you got a *concrete* idea of how something works. Grab
a pencil and a large piece of paper, pretend you are python.exe and
follow through what happens when it executes
ptab = SimplePivotTable(.......)
and the ptab.add_item(......) loop with this set of data:
data = [
['Bob', 'Morn', 240],
['Bob', 'Aft', 300],
['Bob', 'Morn', 40],
]
with the goal of being able to say what is in ptab.cell_dict and
understanding how it got there.

Cheers,
John
Dec 29 '07 #5
Patrick,

in your first posting you are writing "... I'm trying to learn how to
make pivot tables from some excel sheets...". Can you be more specific
please? AFIK Excel offers very good support for pivot tables. So why
to read tabular data from the Excel sheet and than transform it to
pivot tabel in Python?

Petr

Dec 29 '07 #6
On Dec 29, 3:00 pm, petr.jakes....@gmail.com wrote:
Patrick,

in your first posting you are writing "... I'm trying to learn how to
make pivot tables from some excel sheets...". Can you be more specific
please? AFIK Excel offers very good support for pivot tables. So why
to read tabular data from the Excel sheet and than transform it to
pivot tabel in Python?

Petr
Yes, I realize Excel has excellent support for pivot tables. However,
I hate how Excel does it and, for my particular excel files, I need
them to be formated in an automated way because I will have a number
of them over time and I'd prefer just to have python do it in a flash
than to do it every time with Excel.
>It's about time you got a *concrete* idea of how something works.
Absolutely right. I tend to take on ideas that I'm not ready for, in
the sense that I only started using Python some months ago for some
basic tasks and now I'm trying on some more complicated ones. With
time, though, I will get a concrete idea of what python.exe does, but,
for someone who studied art history and not comp sci, I'm doing my
best to get a handle on all of it. I think a pad of paper might be a
good way to visualize it.
Dec 29 '07 #7
Yes, I realize Excel has excellent support for pivot tables. However,
I hate how Excel does it and, for my particular excel files, I need
them to be formated in an automated way because I will have a number
of them over time and I'd prefer just to have python do it in a flash
than to do it every time with Excel.
Patrick,

Few more questions:
- Where the data come from (I mean: are your data in Excel already
when you get them)?

- If your primary source of data is the Excel file, how do you read
data from the Excel
file to Python (I mean did you solve this part of the task already)?

Petr
Dec 29 '07 #8
Yes in the sense that the top part will have merged cells so that
Horror and Classics don't need to be repeated every time, but the
headers aren't the important part. At this point I'm more interested
in organizing the data itself and i can worry about putting it into a
new excel file later.
Jan 3 '08 #9
On Jan 4, 4:55 pm, patrick.wa...@gmail.com wrote:
Petr thanks so much for your input. I'll try to learnSQL, especially
if I'll do a lot of database work.

I tried to do it John's way as en exercise and I'm happy to say I
understand a lot more. Basically I didn't realize I could nest
dictionaries like db = {country:{genre:{sub_genre:3}}} and call them
like db[country][genre][sub_genre]. The Python Cookbook was quite
helpful to figure out why items needed to be added the way they did.
Also using the structure of the dictionary was a conceptually easier
solution than what I found onhttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/334695.

So, now I need to work on writing it to Excel. I'll update with the
final code.
Hi, good to know you have succeded. I think it is matter of taste
which way to go (dictionary or database). My feelig is: for data use
database! If you are trying to work with data, you will need it sooner
or later anyway. Again: database is made for data! :-)

Just save your numbers separated by commas in the file with the
extension csv (my_data.csv) and you can open it directly in Excel.

Good luck :-)

Petr
Jan 4 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.