按0级索引的最后一个值对Pandas MultiIndex进行排序

问题描述 投票:2回答:2

我有一个名为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-05-16的病例值并返回已排序的国家/地区列表

[我曾考虑仅使用2020-05-16值创建另一个df,然后使用df.sort_values()方法,但我确信必须有一种更有效的方法。

虽然我在做这个,但我也试图只选择在2020-05-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)

但是这是一种很差的方法。

[如果有人对如何提高这段代码的效率有想法,我将非常高兴。

谢谢:)

python pandas multi-index
2个回答
2
投票

您可以先按“国家/地区”对数据集进行分组,然后按“日期”对每个组进行排序,取最后一个,然后按“案例”进行再次排序。

自己添加一些数据(数据类型不同,但您明白我的意思):

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

请注意安全!


0
投票
last_recs = df_world.reset_index().groupby('Country/Region').last()
sorted_countries = last_recs.sort_values('Cases')['Country/Region']

由于我没有您的原始数据,所以无法测试它,但这应该可以满足您的需求。我相信所有方法都是不言自明的。

如果不是这种情况,您可能需要按第一行中的日期对df_world进行排序。

© www.soinside.com 2019 - 2024. All rights reserved.