按组对熊猫数据框进行排序,并保持所需的顺序

时间:2019-02-13 05:23:10

标签: python pandas sorting dataframe

我有一个如下所示的数据框

df = pd.DataFrame({
    "Junk":list("aaaaaabbbcccc"),
    "Region":['West','West','West','West','East','East','East','South','South','South','North','North','North'],
    "Sales":[1, 3, 4, 2, 4, 2, 5, 7, 9, 7, 5, 9, 5]
})

+------+--------+-------+
| Junk | Region | Sales |
+------+--------+-------+
| a    | West   |     1 |
| a    | West   |     3 |
| a    | West   |     4 |
| a    | West   |     2 |
| a    | East   |     4 |
| a    | East   |     2 |
| b    | East   |     5 |
| b    | South  |     7 |
| b    | South  |     9 |
| c    | South  |     7 |
| c    | North  |     5 |
| c    | North  |     9 |
| c    | North  |     5 |
+------+--------+-------+

我想做两件事

  1. 根据每个区域对数据框进行排序

我可以使用以下代码实现

df.sort_values(by = ['Region','Sales'])


+------+--------+-------+
| Junk | Region | Sales |
+------+--------+-------+
| a    | East   |     2 |
| a    | East   |     4 |
| b    | East   |     5 |
| c    | North  |     5 |
| c    | North  |     5 |
| c    | North  |     9 |
| b    | South  |     7 |
| c    | South  |     7 |
| b    | South  |     9 |
| a    | West   |     1 |
| a    | West   |     2 |
| a    | West   |     3 |
| a    | West   |     4 |
+------+--------+-------+

但是我想保留Region列的顺序。首先应该是West,然后是East,然后是South,然后是North

所需的输出

+--------+----------+---------+
|  Junk  |  Region  |  Sales  |
+--------+----------+---------+
|  a     | West     |       1 |
|  a     | West     |       2 |
|  a     | West     |       3 |
|  a     | West     |       4 |
|  a     | East     |       2 |
|  a     | East     |       4 |
|  b     | East     |       5 |
|  b     | South    |       7 |
|  c     | South    |       7 |
|  b     | South    |       9 |
|  c     | North    |       5 |
|  c     | North    |       5 |
|  c     | North    |       9 |
+--------+----------+---------+
  1. 我只想对其余的Region = EastRegion = North进行排序

所需的输出:

+--------+----------+---------+
|  Junk  |  Region  |  Sales  |
+--------+----------+---------+
|  a     | West     |       1 |
|  a     | West     |       3 |
|  a     | West     |       4 |
|  a     | West     |       2 |
|  a     | East     |       2 |
|  a     | East     |       4 |
|  b     | East     |       5 |
|  b     | South    |       7 |
|  b     | South    |       9 |
|  c     | South    |       7 |
|  c     | North    |       5 |
|  c     | North    |       5 |
|  c     | North    |       9 |
+--------+----------+---------+

3 个答案:

答案 0 :(得分:5)

首先创建ordered categorical列,然后进行排序:

order = ['West', 'East', 'South', 'North']
df['Region'] = pd.CategoricalIndex(df['Region'], ordered=True, categories=order)

df = df.sort_values(by = ['Region','Sales'])
print (df)
   Junk Region  Sales
0     a   West      1
3     a   West      2
1     a   West      3
2     a   West      4
5     a   East      2
4     a   East      4
6     b   East      5
7     b  South      7
9     c  South      7
8     b  South      9
10    c  North      5
12    c  North      5
11    c  North      9

使用字典创建map的解决方案,并创建新列,订购并删除助手列:

order = {'West':1, 'East':2, 'South':3, 'North':4}

df = df.assign(tmp=df['Region'].map(order)).sort_values(by = ['tmp','Sales']).drop('tmp', 1)
print (df)
   Junk Region  Sales
6     a   West      1
0     a   West      2
7     a   West      3
8     a   West      4
2     a   East      2
1     a   East      4
3     b   East      5
4     b  South      7
9     c  South      7
5     b  South      9
10    c  North      5
12    c  North      5
11    c  North      9

第二步是必须按过滤后的行排序,但要分配numpy数组以防止数据对齐:

order = ['West', 'East', 'South', 'North']
df['Region'] = pd.CategoricalIndex(df['Region'], ordered=True, categories=order)

mask = df['Region'].isin(['North', 'East'])
df[mask] = df[mask].sort_values(['Region','Sales']).values
print (df)
   Junk Region  Sales
0     a   West      1
1     a   West      3
2     a   West      4
3     a   West      2
4     a   East      2
5     a   East      4
6     b   East      5
7     b  South      7
8     b  South      9
9     c  South      7
10    c  North      5
11    c  North      5
12    c  North      9

map替代:

order = {'East':1, 'North':2}
df = df.assign(tmp=df['Region'].map(order))

mask = df['Region'].isin(['North', 'East'])
df[mask] = df[mask].sort_values(['tmp','Sales']).values
df = df.drop('tmp', axis=1)

答案 1 :(得分:2)

您可以使用groupby并利用sort参数。然后在有条件的情况下使用applysort_values

sort_regions = ['North', 'East']
df.groupby('Region', sort=False).apply(
    lambda x: x.sort_values('Sales')
    if x['Region'].iloc[0] in sort_regions
    else x
).reset_index(drop=True)

输出:

   Junk Region  Sales
0     a   West      1
1     a   West      3
2     a   West      4
3     a   West      2
4     a   East      2
5     a   East      4
6     b   East      5
7     b  South      7
8     b  South      9
9     c  South      7
10    c  North      5
11    c  North      5
12    c  North      9

答案 2 :(得分:1)

westeastsouthnorth之间建立到0、1、2、3的映射

>>> my_order = ['West','East','South','North']
>>> order = {key: i for i, key in enumerate(my_order)}
>>> order
{'West': 0, 'East': 1, 'South': 2, 'North': 3}

并使用映射对键进行排序:

>>> df.iloc[df['Region'].map(order).sort_values().index]