我有一个pandas Dataframe(下图),我想做一个非常简单的事情:在每个Climate_type中,不会扰乱Climate_type的顺序:
Climate_type Crop
h. continental cabbage 200.148148
green_beans 226.925926
potato 316.981481
winter_wheat 292.333333
subtropical cabbage 519.925926
green_beans 338.833333
potato 365.740741
spring_wheat 278.388889
temperate cabbage 141.259259
green_beans 165.814815
potato 238.333333
winter_wheat 163.425926
Name: Total_Irrigation_mm, dtype: float64
当我使用sort时,我得到以下内容:
Climate_type Crop
temperate cabbage 141.259259
winter_wheat 163.425926
green_beans 165.814815
h. continental cabbage 200.148148
green_beans 226.925926
temperate potato 238.333333
subtropical spring_wheat 278.388889
h. continental winter_wheat 292.333333
potato 316.981481
subtropical green_beans 338.833333
potato 365.740741
cabbage 519.925926
Name: Total_Irrigation_mm, dtype: float64
你看到Climate_type的顺序不再被保留,这不是我想要的。
答案 0 :(得分:0)
您可以通过对Climate_type
进行分组,然后在每个组内进行排序来完成此操作:
In [54]: s.groupby(level=0, group_keys=False).apply(lambda x: x.order())
Out[54]:
Climate_type Crop
h.continental cabbage 200.148148
green_beans 226.925926
winter_wheat 292.333333
potato 316.981481
subtropical spring_wheat 278.388889
green_beans 338.833333
potato 365.740741
cabbage 519.925926
temperate cabbage 141.259259
winter_wheat 163.425926
green_beans 165.814815
potato 238.333333
dtype: float64
注意:需要group_keys=False
才能在结果中重复使用Climate_type。