Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #97412
| References | <muttuu$pc5$1@ger.gmane.org> |
|---|---|
| Date | 2015-10-06 00:48 +1100 |
| Subject | Re: Finding Blank Columns in CSV |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.390.1444052940.28679.python-list@python.org> (permalink) |
On Tue, Oct 6, 2015 at 12:29 AM, Jaydip Chakrabarty
<chalao.adda@gmail.com> wrote:
> I want to find out the blank columns, that is, fields where all the
> values are blank. Here is my python code.
>
> fn = "tmp1.csv"
> fin = open(fn, 'rb')
> rdr = csv.DictReader(fin, delimiter=',')
> data = list(rdr)
> flds = rdr.fieldnames
> fin.close()
> mt = []
> flag = 0
> for i in range(len(flds)):
> for row in data:
> if len(row[flds[i]]):
> flag = 0
> break
> else:
> flag = 1
> if flag:
> mt.append(flds[i])
> flag = 0
> print mt
>
> I need to know if there is better way to code this.
>
You could do it with a single iteration, something like this:
fn = "tmp1.csv"
fin = open(fn, 'rb')
rdr = csv.DictReader(fin, delimiter=',')
# all the same down to here
blanks = set(rdr.fieldnames)
for row in data:
blanks = {col for col in blanks if not row[col]}
mt = [col for col in rdr.fieldnames if col not in blanks]
print mt
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Finding Blank Columns in CSV Chris Angelico <rosuav@gmail.com> - 2015-10-06 00:48 +1100
csiph-web