对列标签pandas pivot table进行排序

时间:2016-10-20 18:22:50

标签: python pandas

另一个大熊猫排序问题(尝试了所有当前的SO并没有找到任何解决方案)。

我有pandas pivot_table这样:

rows = ['Tool_Location']
cols = ['shift_date','Part_Number', 'shift']
pt = df.pivot_table(index='Tool_Location', values='Number_of_parts', dropna=False, fill_value ='0', columns=cols, aggfunc='count')

产生

Shift date     10/19
Part_number   40001
shift        first  second  third
tool_loc
T01            0     1     0       
T02            2     1     0 

我想切换班次标签的顺序,使其为third first second

修改

更接近解决方案但却没有看到它。

使用:

 col_list = pt.columns.tolist()
 output:
 [('10/20/16', 'first'), ('10/20/16', 'second'), ('10/20/16', 'third'), ('10/21/16', 'first'), ('10/21/16', 'second'), ('10/21/16', 'third')]

任何人都知道如何动态重新排序项目,以便:

[('10/20/16', 'third'), ('10/20/16', 'first'), ('10/20/16', 'second'), ('10/21/16', 'first'), ('10/21/16', 'second'), ('10/21/16', 'second')]

因为那时我们可以使用pt = pt [col_list]

对列重新排序

2 个答案:

答案 0 :(得分:1)

df.pivot_table produces a dataframe. What if you do something like this after your lines:

pt = pt[["third","first","second"]]

答案 1 :(得分:1)

您可以使用lambda和dict对元组进行排序:

.error {
  display: block;
  color: red;
}

要执行此操作,您还需要声明具有所需顺序的字典:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css">
  <title></title>
</head>

<body>

  <div class="container">
    <div class="row">
      <div class="col-8">
        <form action="index.php" class="form">
          <div class="form-group">
            <fieldset>
              <legend>Enter month and year</legend>
              <div id='errors'></div>
              <div class="form-row align-items-center">
                <div class="col">
                  <label class="form-hint" for="month">Month</label>
                  <input type="text" name="month" class="form-control month-validation" id="month" data-msg-required="Enter the month" />
                </div>
                <div class="col">
                  <label class="form-hint" for="year">Year</label>
                  <input type="text" name="year" class="form-control year-validation" id="year" data-msg-required="Enter the year" />
                </div>
              </div>
            </fieldset>
          </div>
          <input type="submit" class="btn btn-primary">
        </form>
      </div>
    </div>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>
</body>

</html>