Franck Dernoncourt
Franck Dernoncourt

Reputation: 83187

Swap axes of a multidimensional Python list

How to swap the axes of a multidimensional Python list?

For example, if the multidimensional Python list is input = [[1,2], [3,4,5],[6]], I would like to have output = [[1,3,6], [2,4], [5]] as output.

numpy.swapaxes allows to do so for an array, but it doesn't support the case where a dimension has a varying size, as in the given example. Same issue with the typical map(list, zip(*l)).

Upvotes: 2

Views: 4744

Answers (2)

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

Try this:

from itertools import izip_longest
print [[i for i in element if i is not None] for element in  list(izip_longest(*input))]

Output:

[[1, 3, 6], [2, 4], [5]]

(iterools.izip_longest was introduced in Python 2.6.)

Upvotes: 5

gabra
gabra

Reputation: 10564

Try this:

import numpy as np
import pandas as pd

input  = [[1,2], [3,4,5],[6]]

df = pd.DataFrame(input).T

output = [[element for element in row if not np.isnan(element)] for row in df.values]

Output

 [[1.0, 3.0, 6.0], [2.0, 4.0], [5.0]]

Upvotes: 2

Related Questions