Finding Blank Columns in CSV
Friedrich Rentsch
anthra.norell at bluewin.ch
Mon Oct 5 16:08:33 EDT 2015
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
More information about the Python-list
mailing list