按具有多个值的列对 DF 进行排序

Sorting DF by a column with multiple values

在我的主 df 中,我有一个与其他两个列组合的列,创建的值如下所示:A1_43567_1。第一个数字代表所采取的评估类型,第二个数字是问题 ID,最后一个数字是评估中的问题位置。我计划创建一个数据透视表 table 以将每个唯一值作为一列来查看每个项目的多个学生的选择。但我希望枢轴的顺序由问题位置或串联中的第三个值决定。基本上这个输出:

    Student ID  A1_45678_1  A1_34551_2  A1_11134_3  etc....
    12345           1            0          0      
    12346           0            0          1
    12343           1            1          0

我已经尝试按原始列对我的数据框进行排序,我希望它按(问题位置)进行排序,然后创建枢轴 table,但这并没有呈现上述结果我'我在找。有没有办法按列中的第三个值对原始串联值进行排序?或者是否可以按每列中的第三个值对主元 table 进行排序?

当前代码是:

   demo_pivot.sort(['Question Position'], ascending=True)

   demo_pivot['newcol'] = 'A' + str(interim_selection) + '_' + ,\
   demo_pivot['Item ID'].map(str) + "_" + demo_pivot['Question Position'].map(str)

   demo_pivot= pd.pivot_table(demo_pivot, index='Student ANET ID',values='Points Received',\
   columns='newcol').reset_index()

但生成此输出:

    Student ID  A1_45678_1  A1_34871_7  A1_11134_15  etc....
    12345           1            0          0      
    12346           0            0          1
    12343           1            1          0

pd.pivot_table() returns DataFrame 的调用,正确吗?如果是这样,您可以只对结果 DataFrame 的列重新排序吗?类似于:

def sort_columns(column_list):
    # Create a list of tuples: (question position, column name)
    sort_list = [(int(col.split('_')[2]), col) for col in column_list]

    # Sorts by the first item in each tuple, which is the question position
    sort_list.sort() 

    # Return the column names in the sorted order:
    return [x[1] for x in sort_list]

# Now, you should be able to reorder the DataFrame like so:
demo_pivot = demo_pivot.loc[:, sort_columns(demo_pivot.columns)]