<p>耶斯雷尔的解决方案当然是正确的,而且很可能是最快的。但由于这实际上只是一个重构数据帧的问题,我想向您展示如何轻松地做到这一点,同时让您的过程选择要使用的排序列的子集</p>
<p>以下非常简单的函数将允许您指定数据帧的子集和顺序:</p>
<pre><code># function to subset and order a pandas
# dataframe of a long format
def order_df(df_input, order_by, order):
df_output=pd.DataFrame()
for var in order:
df_append=df_input[df_input[order_by]==var].copy()
df_output = pd.concat([df_output, df_append])
return(df_output)
</code></pre>
<p>下面是一个使用plotly express中的iris数据集的示例<code>df['species'].unique()</code>将显示该列的顺序:</p>
<p><strong>输出:</strong></p>
<pre><code>array(['setosa', 'versicolor', 'virginica'], dtype=object)
</code></pre>
<p>现在,使用上面的函数运行下面的完整代码段将为您提供一个新的指定顺序。不需要分类变量或篡改索引</p>
<p><strong>使用数据示例完成代码:</strong></p>
<pre><code># imports
import pandas as pd
import plotly.express as px
# data
df = px.data.iris()
# function to subset and order a pandas
# dataframe fo a long format
def order_df(df_input, order_by, order):
df_output=pd.DataFrame()
for var in order:
df_append=df_input[df_input[order_by]==var].copy()
df_output = pd.concat([df_output, df_append])
return(df_output)
# data subsets
df_new = order_df(df_input = df, order_by='species', order=['virginica', 'setosa', 'versicolor'])
df_new['species'].unique()
</code></pre>
<p><strong>输出:</strong></p>
<pre><code>array(['virginica', 'setosa', 'versicolor'], dtype=object)
</code></pre>