擅长:python、mysql、java
<p>您可以从extract column数据创建元组并将其传递给函数<code>pd.MultiIndex.from_tuples()</code>这将生成列,然后您可以重新创建dataframe。请在下面找到代码。在</p>
<pre><code>import pandas as pd
import numpy as np
pd.set_option('display.multi_sparse', False)
values = [[1, 3, 5], [2, 4, 6]]
df = pd.DataFrame(values,columns=['Base + Trial Spot Price(X220) Settle Price S=1 [1.00] 1932', 'Base + Trial Spot Price(Y220) Settle Price S=1 [1.00] 2012', 'Base + Trial Spot Price(Y220) Settle Price S=1 [1.00] 2015'])
cols = pd.MultiIndex.from_tuples([(df.columns[0][24:28], df.columns[0][54:]), (df.columns[1][24:28], df.columns[0][54:]), (df.columns[2][24:28], df.columns[0][54:])])
pd.DataFrame(values, columns=cols)
</code></pre>
<p><strong>输出:</strong></p>
^{pr2}$
<p>行<code>pd.set_option('display.multi_sparse', False)</code>用于将多轴配置为具有重复的列名。在</p>
<p><strong>参考文献:</strong></p>
<ol>
<li><a href="https://pandas.pydata.org/pandas-docs/stable/advanced.html" rel="nofollow noreferrer">MultiIndex / Advanced Indexing — pandas documentation</a></li>
</ol>