交换多维 Python 列表的轴

Swap axes of a multidimensional Python list

如何交换多维Python列表的坐标轴?

例如,如果多维 Python 列表是 input = [[1,2], [3,4,5],[6]],我希望将 output = [[1,3,6], [2,4], [5]] 作为输出。

numpy.swapaxes 允许对数组这样做,但它不支持维度具有不同大小的情况,如给定示例中所示。与典型 map(list, zip(*l)).

相同的问题

试试这个:

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

输出:

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

iterools.izip_longest 是在 Python 2.6 中引入的。)

试试这个:

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]

输出

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