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 20 1899
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
> 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}
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
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.
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
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/
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/
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
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 ... This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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
#
|
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):
|
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...
|
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.
|
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...
| |
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,...
|
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...
|
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...
|
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,...
|
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...
|
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...
| |
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |