473,624 Members | 2,534 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"groupby" is brilliant!

Hi all

This is probably old hat to most of you, but for me it was a
revelation, so I thought I would share it in case someone has a similar
requirement.

I had to convert an old program that does a traditional pass through a
sorted data file, breaking on a change of certain fields, processing
each row, accumulating various totals, and doing additional processing
at each break. I am not using a database for this one, as the file
sizes are not large - a few thousand rows at most. I am using csv
files, and using the csv module so that each row is nicely formatted
into a list.

The traditional approach is quite fiddly, saving the values of the
various break fields, comparing the values on each row with the saved
values, and taking action if the values differ. The more break fields
there are, the fiddlier it gets.

I was going to do the same in python, but then I vaguely remembered
reading about 'groupby'. It took a little while to figure it out, but
once I had cracked it, it transformed the task into one of utter
simplicity.

Here is an example. Imagine a transaction file sorted by branch,
account number, and date, and you want to break on all three.

-----------------------------
import csv
from itertools import groupby
from operator import itemgetter

BRN = 0
ACC = 1
DATE = 2

reader = csv.reader(open ('trans.csv', 'rb'))
rows = []
for row in reader:
rows.append(row )

for brn,brnList in groupby(rows,it emgetter(BRN)):
for acc,accList in groupby(brnList ,itemgetter(ACC )):
for date,dateList in groupby(accList ,itemgetter(DAT E)):
for row in dateList:
[do something with row]
[do something on change of date]
[do something on change of acc]
[do something on change of brn]
-----------------------------

Hope someone finds this of interest.

Frank Millman

Jun 13 '06 #1
20 1899
vpr
Hi Frank

This is one of the reasons why I love Python, you can write readable
code.
I strive to write clean code but I find that exception handling code
e.g. try:
makes my code ugly and significantly harder to read. Does anyone have
any good
pointers for a former C++ / Perl coder.

/vpr
Frank Millman wrote:
Hi all

This is probably old hat to most of you, but for me it was a
revelation, so I thought I would share it in case someone has a similar
requirement.

I had to convert an old program that does a traditional pass through a
sorted data file, breaking on a change of certain fields, processing
each row, accumulating various totals, and doing additional processing
at each break. I am not using a database for this one, as the file
sizes are not large - a few thousand rows at most. I am using csv
files, and using the csv module so that each row is nicely formatted
into a list.

The traditional approach is quite fiddly, saving the values of the
various break fields, comparing the values on each row with the saved
values, and taking action if the values differ. The more break fields
there are, the fiddlier it gets.

I was going to do the same in python, but then I vaguely remembered
reading about 'groupby'. It took a little while to figure it out, but
once I had cracked it, it transformed the task into one of utter
simplicity.

Here is an example. Imagine a transaction file sorted by branch,
account number, and date, and you want to break on all three.

-----------------------------
import csv
from itertools import groupby
from operator import itemgetter

BRN = 0
ACC = 1
DATE = 2

reader = csv.reader(open ('trans.csv', 'rb'))
rows = []
for row in reader:
rows.append(row )

for brn,brnList in groupby(rows,it emgetter(BRN)):
for acc,accList in groupby(brnList ,itemgetter(ACC )):
for date,dateList in groupby(accList ,itemgetter(DAT E)):
for row in dateList:
[do something with row]
[do something on change of date]
[do something on change of acc]
[do something on change of brn]
-----------------------------

Hope someone finds this of interest.

Frank Millman


Jun 13 '06 #2
>
reader = csv.reader(open ('trans.csv', 'rb'))
rows = []
for row in reader:
rows.append(row )


This is untested, but you might think about converting your explicit "for...
append" loop into either a list comp,

rows = [row for row in reader]

or just a plain list constructor:

rows = list(reader)

Neh?

-- Paul
(Oh, and I like groupby too! Combine it with sort to quickly create
histograms.)

# tally a histogram of a list of values from 1-10
dataValueRange = range(1,11)
data = [random.choice(d ataValueRange) for i in xrange(10000)]

hist = [ (k,len(list(g)) ) for k,g in itertools.group by(sorted(data) ) ]
print hist

histAsDict = dict((k,len(lis t(g))) for k,g in
itertools.group by(sorted(data) ))
print histAsDict

Gives:

[(1, 979), (2, 1034), (3, 985), (4, 969), (5, 1020), (6, 975), (7, 981), (8,
1070), (9, 1003), (10, 984)]
{1: 979, 2: 1034, 3: 985, 4: 969, 5: 1020, 6: 975, 7: 981, 8: 1070, 9: 1003,
10: 984}
Jun 13 '06 #3

Paul McGuire wrote:

reader = csv.reader(open ('trans.csv', 'rb'))
rows = []
for row in reader:
rows.append(row )


This is untested, but you might think about converting your explicit "for...
append" loop into either a list comp,

rows = [row for row in reader]

or just a plain list constructor:

rows = list(reader)

Neh?

-- Paul


Yup, they both work fine.

There may be times when you want to massage the data before appending
it, in which case you obviously have to do it the long way. Otherwise
these are definitely neater, the last one especially.

You could even do it as a one-liner -
rows = list(csv.reader (open('trans.cs v', 'rb')))

It still looks perfectly readable to me.

Thanks

Frank

Jun 13 '06 #4
Frank;
I would just like to thank-you for this timely post.
I am working on a reporting project that needed "groupby" functionality
and I was going to sit down this morning to rework some "very ugly
code" into some "not quite so ugly code".

Your post got me pointed to in the "right" direction and the end
results will be much more flexible and ALOT more maintainable.

Thanks.

Jun 13 '06 #5
Frank Millman wrote:
reader = csv.reader(open ('trans.csv', 'rb'))
rows = []
for row in reader:
rows.append(row )


Why do you create a list of rows instead of just iterating over the
reader directly?
--
Benji York
Jun 13 '06 #6
Frank Millman wrote:
Hi all

This is probably old hat to most of you, but for me it was a
revelation, so I thought I would share it in case someone has a similar
requirement.

I had to convert an old program that does a traditional pass through a
sorted data file, breaking on a change of certain fields, processing
each row, accumulating various totals, and doing additional processing
at each break. I am not using a database for this one, as the file
sizes are not large - a few thousand rows at most. I am using csv
files, and using the csv module so that each row is nicely formatted
into a list.

The traditional approach is quite fiddly, saving the values of the
various break fields, comparing the values on each row with the saved
values, and taking action if the values differ. The more break fields
there are, the fiddlier it gets.

I was going to do the same in python, but then I vaguely remembered
reading about 'groupby'. It took a little while to figure it out, but
once I had cracked it, it transformed the task into one of utter
simplicity.

Here is an example. Imagine a transaction file sorted by branch,
account number, and date, and you want to break on all three.

-----------------------------
import csv
from itertools import groupby
from operator import itemgetter

BRN = 0
ACC = 1
DATE = 2

reader = csv.reader(open ('trans.csv', 'rb'))
rows = []
for row in reader:
rows.append(row )

for brn,brnList in groupby(rows,it emgetter(BRN)):
for acc,accList in groupby(brnList ,itemgetter(ACC )):
for date,dateList in groupby(accList ,itemgetter(DAT E)):
for row in dateList:
[do something with row]
[do something on change of date]
[do something on change of acc]
[do something on change of brn]
-----------------------------

Hope someone finds this of interest.

Frank Millman


I'm sure I'm going to get a lot of flac on this list for proposing to
turn nested for-loops into a recursive function, but I couldn't help
myself. This seems more simple to me, but for others it may be difficult
to look at, and these people will undoubtedly complain.
import csv
from itertools import groupby
from operator import itemgetter

reader = csv.reader(open ('trans.csv', 'rb'))
rows = []
for row in reader:
rows.append(row )

def brn_doer(row):
[doing something with brn here]

def acc_doer(date):
[you get the idea]

[etc.]

doers = [brn_doer, acc_doer, date_doer, row_doer]

def doit(rows, doers, i=0):
for r, alist in groupby(rows, itemgetter(i)):
doit(alist, doers[1:], i+1)
doers[0](r)

doit(rows, doers, 0)

Now all of those ugly for loops become one recursive function. Bear in
mind, its not all that 'elegant', but it looks nicer, is more succinct,
abstracts the process, and scales to arbitrary depth. Tragically,
however, it has been generalized, which is likely to raise some hackles
here. And, oh yes, it didn't answer exactly your question (which you
didn't really have). I'm sure I will regret this becuase, as you will
find, suggesting code on this list with additional utility is somewhat
discouraged by the vociferous few who make a religion out of 'import this'.

Also, I still have no idea what 'groupby' does. It looks interesting
thgough, thanks for pointing it out.

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jun 13 '06 #7
James Stroud wrote:
Frank Millman wrote:
Hi all

This is probably old hat to most of you, but for me it was a
revelation, so I thought I would share it in case someone has a similar
requirement.

I had to convert an old program that does a traditional pass through a
sorted data file, breaking on a change of certain fields, processing
each row, accumulating various totals, and doing additional processing
at each break. I am not using a database for this one, as the file
sizes are not large - a few thousand rows at most. I am using csv
files, and using the csv module so that each row is nicely formatted
into a list.

The traditional approach is quite fiddly, saving the values of the
various break fields, comparing the values on each row with the saved
values, and taking action if the values differ. The more break fields
there are, the fiddlier it gets.

I was going to do the same in python, but then I vaguely remembered
reading about 'groupby'. It took a little while to figure it out, but
once I had cracked it, it transformed the task into one of utter
simplicity.

Here is an example. Imagine a transaction file sorted by branch,
account number, and date, and you want to break on all three.

-----------------------------
import csv
from itertools import groupby
from operator import itemgetter

BRN = 0
ACC = 1
DATE = 2

reader = csv.reader(open ('trans.csv', 'rb'))
rows = []
for row in reader:
rows.append(row )

for brn,brnList in groupby(rows,it emgetter(BRN)):
for acc,accList in groupby(brnList ,itemgetter(ACC )):
for date,dateList in groupby(accList ,itemgetter(DAT E)):
for row in dateList:
[do something with row]
[do something on change of date]
[do something on change of acc]
[do something on change of brn]
-----------------------------

Hope someone finds this of interest.

Frank Millman


I'm sure I'm going to get a lot of flac on this list for proposing to
turn nested for-loops into a recursive function, but I couldn't help
myself. This seems more simple to me, but for others it may be difficult
to look at, and these people will undoubtedly complain.
import csv
from itertools import groupby
from operator import itemgetter

reader = csv.reader(open ('trans.csv', 'rb'))
rows = []
for row in reader:
rows.append(row )

def brn_doer(row):
[doing something with brn here]

def acc_doer(date):
[you get the idea]

[etc.]

doers = [brn_doer, acc_doer, date_doer, row_doer]

def doit(rows, doers, i=0):
for r, alist in groupby(rows, itemgetter(i)):
doit(alist, doers[1:], i+1)
doers[0](r)

doit(rows, doers, 0)

Now all of those ugly for loops become one recursive function. Bear in
mind, its not all that 'elegant', but it looks nicer, is more succinct,
abstracts the process, and scales to arbitrary depth. Tragically,
however, it has been generalized, which is likely to raise some hackles
here. And, oh yes, it didn't answer exactly your question (which you
didn't really have). I'm sure I will regret this becuase, as you will
find, suggesting code on this list with additional utility is somewhat
discouraged by the vociferous few who make a religion out of 'import this'.

Also, I still have no idea what 'groupby' does. It looks interesting
thgough, thanks for pointing it out.

James


Forgot to test for stopping condition:
def doit(rows, doers, i=0):
for r, alist in groupby(rows, itemgetter(i)):
if len(doers) > 1:
doit(alist, doers[1:], i+1)
doers[0](r)

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jun 13 '06 #8
Not related to itertools.group by, but the csv.reader object...

If for some reason you have malformed CSV files, with embedded newlines
or something of that effect, it will raise an exception. To skip those,
you will need a construct of something like this:

raw_csv_in = file('filenameh ere.csv')
for raw_line in raw_csv_in:
try:
# Do something to rawline here maybe if necessary to "clean it
up"
row = csv.reader( [raw_line] ).next()
# Do your stuff here
except csv.Error:
pass # or do something more appropriate if the record is
important

May not be applicable in your case, but has stung me a few times...

All the best,

Jon.
Frank Millman wrote:
Paul McGuire wrote:

reader = csv.reader(open ('trans.csv', 'rb'))
rows = []
for row in reader:
rows.append(row )


This is untested, but you might think about converting your explicit "for...
append" loop into either a list comp,

rows = [row for row in reader]

or just a plain list constructor:

rows = list(reader)

Neh?

-- Paul


Yup, they both work fine.

There may be times when you want to massage the data before appending
it, in which case you obviously have to do it the long way. Otherwise
these are definitely neater, the last one especially.

You could even do it as a one-liner -
rows = list(csv.reader (open('trans.cs v', 'rb')))

It still looks perfectly readable to me.

Thanks

Frank


Jun 13 '06 #9
On 13/06/2006 6:28 PM, Paul McGuire wrote:
(Oh, and I like groupby too! Combine it with sort to quickly create
histograms.)

# tally a histogram of a list of values from 1-10
dataValueRange = range(1,11)
data = [random.choice(d ataValueRange) for i in xrange(10000)]

hist = [ (k,len(list(g)) ) for k,g in itertools.group by(sorted(data) ) ]


That len(list(g)) looks like it uses O(N) memory just to find out what N
is :-(

The best I could come up with is sum(itertools.i map(lambda x: 1, g)) --
but that does look a bit ugly ...

Jun 13 '06 #10

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

Similar topics

35
2932
by: les_ander | last post by:
Hi, I know that i can do readline() from a file object. However, how can I read till a specific seperator? for exmple, if my files are name profession id #
42
2605
by: Alan McIntyre | last post by:
Hi all, I have a list of items that has contiguous repetitions of values, but the number and location of the repetitions is not important, so I just need to strip them out. For example, if my original list is , I want to end up with . Here is the way I'm doing this now: def straightforward_collapse(myList):
15
2122
by: Jordan Rastrick | last post by:
First, a disclaimer. I am a second year Maths and Computer Science undergraduate, and this is my first time ever on Usenet (I guess I'm part of the http generation). On top of that, I have been using Python for a grand total of about a fortnight now. Hence, I apologise if what follows is a stupid suggestion, or if its already been made somewhere else, or if this is not the appropriate place to make it, etc. But I did honestly do some...
5
1750
by: chirayuk | last post by:
Hi, I am trying to treat an environment variable as a python list - and I'm sure there must be a standard and simple way to do so. I know that the interpreter itself must use it (to process $PATH / %PATH%, etc) but I am not able to find a simple function to do so. os.environ.split(os.sep) is wrong on Windows for the case when PATH="c:\\A;B";c:\\D; where there is a ';' embedded in the quoted path.
0
8231
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8168
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8672
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8614
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8330
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7153
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6107
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5561
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4167
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.