<p>创建一个分组序列<code>g</code>,我们需要对数据帧进行分组,以便每三个元素(步长为3)都属于同一个组,使用<a href="https://numpy.org/doc/stable/reference/generated/numpy.unique.html" rel="nofollow noreferrer">^{<cd2>}</a>获取唯一的分组键,接下来使用<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">^{<cd3>}</a>对<code>g</code>上的数据帧进行分组,并使用<code>set_index</code>将每个分组帧的索引设置为<code>k</code>,最后使用<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer">^{<cd7>}</a>沿<code>axis=1</code>连接所有分组的数据帧,并传递可选参数<code>keys=k</code>以创建<code>MultiLevel</code>列
:</p>
<pre><code>g, k = df.pop('e').sub(1) % 3 + 1, np.unique(g)
df1 = pd.concat([g.set_index(k) for _, g in df.groupby(g)], keys=k, axis=1)
</code></pre>
<p>详情:</p>
<pre><code>print(g.tolist())
[1, 2, 3, 1, 2, 3, 1, 2, 3]
print(k)
array([1, 2, 3])
</code></pre>
<p>结果:</p>
<pre><code>print(df1)
1 2 3
col1 col2 col3 col1 col2 col3 col1 col2 col3
1 238.40 238.70 238.20 238.45 238.75 238.2 238.20 238.25 237.95
2 238.10 238.15 238.05 238.10 238.10 238.0 229.10 229.05 229.05
3 229.35 229.35 229.10 229.10 229.15 229.0 229.05 229.05 229.00
</code></pre>