reshape
+ swapaxes
+ reshape
df.values.reshape(-1, 3, 3).swapaxes(1, 0).reshape(-1, 3)
array([['A1', 'B1', 'C1'],
['A2', 'B2', 'C2'],
['A3', 'B3', 'C3'],
['A4', 'B4', 'C4'],
['A5', 'B5', 'C5'],
['A6', 'B6', 'C6'],
['A7', 'B7', 'C7'],
['A8', 'B8', 'C8'],
['A9', 'B9', 'C9']], dtype=object)
为了更加通用,您可以根据分组计算偏移量。例如,在以下框架中,让我们将每4列分为一组:
A1 B1 C1 D1 A4 B4 C4 D4 A7 B7 C7 D7
A2 B2 C2 D2 A5 B5 C5 D5 A8 B8 C8 D8
A3 B3 C3 D3 A6 B6 C6 D6 A9 B9 C9 D9
n = 4
f = df.shape[1] // n
df.values.reshape(-1, f, n).swapaxes(1, 0).reshape(-1, n)
array([['A1', 'B1', 'C1', 'D1'],
['A2', 'B2', 'C2', 'D2'],
['A3', 'B3', 'C3', 'D3'],
['A4', 'B4', 'C4', 'D4'],
['A5', 'B5', 'C5', 'D5'],
['A6', 'B6', 'C6', 'D6'],
['A7', 'B7', 'C7', 'D7'],
['A8', 'B8', 'C8', 'D8'],
['A9', 'B9', 'C9', 'D9']], dtype=object)
使用底层数组将是一种非常快速的方法。
df = pd.concat([df]*500)
In [128]: %%timeit
...: n = 3
...: f = df.shape[1] // n
...: df.values.reshape(-1, f, n).swapaxes(1, 0).reshape(-1, n)
...:
77.4 µs ± 417 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [129]: %%timeit
...: c = np.arange(len(df.columns))
...: df.columns = [c // 3, c % 3]
...: df1 = df.stack(0).sort_index(level=1).reset_index(drop=True)
...:
...:
12.2 ms ± 326 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
df.values.reshape(-1,3)
。 - Quang Hoang