skyfail - 1 month ago 5

Python Question

So I have a list of list :-

`a = [[1,2,3,4],[5,6,7,8],[4,5,6,7]]`

I want to iterate through the contents and avoid a certain column. So my general for loop structure is as follows:

`for i in range (0,len(a[0])):`

Now as far as I know I need one more condition to avoid a certain column. How do I do that?

Another way this could be done is to delete the whole column and append it right to the end.

So after deleting the column:

`a = [[1,2,4],[5,6,8],[4,5,7]]`

After appending:

`a = [[1,2,4,3],[5,6,8,7],[4,5,7,6]]`

I could use numpy to do this. So I am deleting the desired column from numpy.

Here's a working code:

`a = [[1,2,3,4],[5,6,7,8],[4,5,6,7]]`

a_np= np.array(a)

a_col_data = a_np[:,2]

a1 = np.delete(a_np, 2 , axis = 1)

Now my a_col_data is

`[3 7 6]`

I cannot append in this format. I need it in this format

`[[3],[7],[6]]`

Then I could use the following code to append it as a last column in a:

`np.append(a_np, a_col_data, axis=1)`

Now issues with this approach, that I am facing:

How to convert a list

`[3 7 6]`

`[[3],[7],[6]]`

Considering I have a list of 150 columns and 3000 rows I can't do it manually.

Another issue is np.array converts the list into a pure matrix like structure removing the "," between elements. I want to get the list structure back.

For example:

`a = [[1,2,4],[5,6,8],[4,5,7]]`

a_np = [[1 2 4][5 6 8][4 5 7]]

How do I convert a_np to a again?

EDIT:

Ok I was just browsing stackoverflow and I got a solution. I could simply do the following to convert it back:

`a_np.tolist()`

Answer

There are many ways to do this.

You could add an extra axis to `a_col_data`

:

```
>>> a_np2 = np.append(a1, a_col_data[:, np.newaxis], axis=1)
>>> a_np2
array([[1, 2, 4, 3],
[5, 6, 8, 7],
[4, 5, 7, 6]])
>>> a_np2.tolist()
[[1, 2, 4, 3], [5, 6, 8, 7], [4, 5, 7, 6]]
```

Or you could avoid going the numpy route by using `enumerate`

:

```
a = [[1,2,3,4],[5,6,7,8],[4,5,6,7]]
for i in a:
for j, x in enumerate(i):
if j == 2:
continue
...
```