scopedial
scopedial

Reputation: 203

How do I remove an empty column in a two dimensional list in python?

My python script imports formatted Excel spreadsheets into a 2 dimensional list. Empty columns can appear at random indexes and I wish to remove all of them. What would be the best way of doing this?

Any advice is appreciated,

Lou

Upvotes: 1

Views: 2755

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208565

Transpose the array so the inner lists are columns, remove empty inner lists, and transpose it again:

data = zip(*data)
data = [x for x in data if any(x)]
data = zip(*data)

If it is an issue for the rows to be converted to tuples, replace the last line with the following:

data = [list(row) for row in zip(*data)]

This is assuming that your inner lists are rows and not columns, if your inner lists already represent a column then you can just do the following (no transposing necessary):

data = [x for x in data if any(x)]

Upvotes: 5

Tommy
Tommy

Reputation: 13672

From the tutorial:

The following list comprehension will transpose rows and columns:

[[row[i] for row in matrix] for i in range(lenOfEachRow)]

One idea is to transpose it, linearly check each row for all 0s, delete that row (simply using delete[indexOfRow] then transpose it back.

Upvotes: 0

Related Questions