![](/img/trans.png)
[英]Custom sorting of the level 1 index of a multiindex Pandas DataFrame according to the level 0 index
[英]Sorting Pandas MultiIndex by the last value of level 0 index
我有一個名為df_world
的 df,其形狀如下:
Cases Death Delta_Cases Delta_Death
Country/Region Date
Brazil 2020-01-22 0.0 0 NaN NaN
2020-01-23 0.0 0 0.0 0.0
2020-01-24 0.0 0 0.0 0.0
2020-01-25 0.0 0 0.0 0.0
2020-01-26 0.0 0 0.0 0.0
... ... ... ...
World 2020-05-12 4261747.0 291942 84245.0 5612.0
2020-05-13 4347018.0 297197 85271.0 5255.0
2020-05-14 4442163.0 302418 95145.0 5221.0
2020-05-15 4542347.0 307666 100184.0 5248.0
2020-05-16 4634068.0 311781 91721.0 4115.0
我想按最后一次記錄中“案例”列的值對國家索引進行排序,即比較所有國家/地區 2020 年 5 月 16 日的案例值並返回排序后的國家/地區列表
我考慮過僅使用 2020-05-16 值創建另一個 df,然后使用df.sort_values()
方法,但我確信必須有更有效的方法。
當我這樣做時,我還嘗試僅 select 那些在 2020 年 5 月 16 日有許多病例超過一定值的國家,我發現這樣做的唯一方法是遍歷國家索引:
for a_country in df_world.index.levels[0]:
if df_world.loc[(a_country, last_date), 'Cases'] < cut_off_val:
df_world = df_world.drop(index=a_country)
但這是一種非常糟糕的方法。
如果有人對如何提高此代碼的效率有任何想法,我將非常高興。
謝謝:)
您可以先按“國家/地區”對數據集進行分組,然后按“日期”對每個組進行排序,取最后一個,然后按“案例”再次排序。
自己偽造一些數據(數據類型不同,但你明白我的意思):
df = pd.DataFrame([['a', 1, 100],
['a', 2, 10],
['b', 2, 55],
['b', 3, 15],
['c', 1, 22],
['c', 3, 80]])
df.columns = ['country', 'date', 'cases']
df = df.set_index(['country', 'date'])
print(df)
# cases
# country date
# a 1 100
# 2 10
# b 2 55
# 3 15
# c 1 22
# 3 80
然后,
# group them by country
grp_by_country = df.groupby(by='country')
# for each group, aggregate by sorting by data and taking the last row (latest date)
latest_per_grp = grp_by_country.agg(lambda x: x.sort_values(by='date').iloc[-1])
# sort again by cases
sorted_by_cases = latest_per_grp.sort_values(by='cases')
print(sorted_by_cases)
# cases
# country
# a 10
# b 15
# c 80
注意安全!
last_recs = df_world.reset_index().groupby('Country/Region').last()
sorted_countries = last_recs.sort_values('Cases')['Country/Region']
由於我沒有您的原始數據,因此無法對其進行測試,但這應該可以滿足您的需要。 我相信所有方法都是不言自明的。
如果不是這種情況,您可能需要按第一行中的日期對 df_world 進行排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.