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

标签 python sorting pandas pivot-table columnsorting

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

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

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

当前代码是:

   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() 返回一个 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)] 

关于python - 按具有多个值的列对 DF 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32634476/

相关文章:

python - pandas groupby column 然后根据第三列创建另外两列

javascript - Python Mechanize - 选择一个值并提交不起作用

python - 使用 pandas 进行代码/循环优化以创建两个矩阵

javascript - 如何按升序对奇数数组进行排序,但将偶数保留在其位置?

javascript - 根据angularjs中 Canvas 上的位置对列表项进行排序

python - 检查某个字符串的 Dataframe 并返回在其中找到该字符串的列的列标题

python - 如何在 Python Pandas 中处理由于夏令时而具有可变时区偏移的时间序列?

python - gitpython 列出所有存储库

python - 如何在python中从类B调用类A中的方法?我收到 "self is not defined"

javascript - 对字符串数字进行排序,angularjs