Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #97424

Re: Finding Blank Columns in CSV

Subject Re: Finding Blank Columns in CSV
References <muttuu$pc5$1@ger.gmane.org>
From Friedrich Rentsch <anthra.norell@bluewin.ch>
Date 2015-10-05 22:08 +0200
Newsgroups comp.lang.python
Message-ID <mailman.403.1444075780.28679.python-list@python.org> (permalink)

Show all headers | View raw



On 10/05/2015 03:29 PM, Jaydip Chakrabarty wrote:
> Hello,
>
> I have a csv file like this.
>
> Name,Surname,Age,Sex
> abc,def,,M
> ,ghi,,F
> jkl,mno,,
> pqr,,,F
>
> 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.
>
> Thanks.
>
Operations on columns are often simpler, if a table is rotated 
beforehand. Columns become lists.

def find_empty_columns (table):
     number_of_records = len (table)
     rotated_table = zip (*table)
     indices_of_empty_columns = []
     for i in range (len (rotated_table)):  # Column indices
         if rotated_table[i].count ('') == number_of_records:
             indices_of_empty_columns.append (i)
     return indices_of_empty_columns

Frederic

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Finding Blank Columns in CSV Friedrich Rentsch <anthra.norell@bluewin.ch> - 2015-10-05 22:08 +0200

csiph-web