pandas 我如何对某个列上的 Dataframe 进行排序?

vbopmzt1  于 2023-04-18  发布在  其他
关注(0)|答案(2)|浏览(131)

我有以下代码:

import pandas as pd
DF = pd.DataFrame({
    "item_id": [1, 2, 3, 4, 5, 6, 7, 8, 9],
    "custumer": ["CG", "CGD", "CC", "CZ", "JD", "KD", "MM", "MK", "JJ"],
    "costs": [150, 12, 78, 56, 5, 6, 4, 68, 69],
    "games": [["Minecraft", "Uno"], ["WOW", "Minecraft"], ["WOW", "Minecraft"], ["WOW", "Minecraft", "The last of us"], ["Monopoly"], ["Monopoly", "Uno"], ["WOW", "Monopoly"], ["Uno", "SkipBo"], ["Schach", "Uno"]], 
    "date": ["2022-01-18", "2022-03-12", "2022-02-26", "2021-11-12", "2021-10-09", "2021-11-26", "2021-10-18", "2021-12-22", "2021-09-06"]
})

DF["games"] = [i[-1:] for i in DF["games"]]
DF["Day"] = pd.to_datetime(DF["date"]).dt.day
DF["Month"] = pd.to_datetime(DF["date"]).dt.month
DF["Year"] = pd.to_datetime(DF["date"]).dt.year
DF #(look at pic_1)

newDF_month = DF.drop(columns=["item_id", "custumer", "games", "date", "Day", "Year"])
newDF_month.groupby(["Month"]).sum()

但是,这表示使用排序(1,2,3,9,10,11,12)按月排序的数据:

month | costs
-------------
   1  | 150
   2  |  78
   3  |  12
   9  |  69
  10  |   9
  11  |  62
  12  |  68

但我想让排序为(9,10,11,12,1,2,3):

month | costs
-------------
   9  |  69
  10  |   9
  11  |  62
  12  |  68
   1  | 150
   2  |  78
   3  |  12

我该怎么做?

tsm1rwdh

tsm1rwdh1#

另一种可能的解决方案:

new = newDF_month.groupby(["Month"]).sum()
m = new.index >= 9
pd.concat([new.loc[m, :], new.loc[~m, :]])

输出:

costs
Month       
9         69
10         9
11        62
12        68
1        150
2         78
3         12
wgxvkvu9

wgxvkvu92#

你可以对它的移位值取12的模sort_index

(newDF_month
 .groupby(["Month"]).sum()
 .sort_index(key=lambda i: (i-9)%12)
)

输出:

costs
Month       
9         69
10         9
11        62
12        68
1        150
2         78
3         12

相关问题