You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按天数统计对Pandas DataFrame的国家排序并返回字符串数组

按国家天数总和排序生成字符串数组

原始DataFrame数据

datedayscountry
2022-02-011Spain
2022-02-022Spain
2022-02-013Italy
2022-02-032France
2022-02-031Germany
2022-02-041Italy
2022-02-041UK
2022-02-052UK
2022-02-045Spain
2022-02-041Portugal

需求说明

按国家汇总days列的总和,按总和从多到少排序,最终生成对应的国家字符串数组。

统计结果

countrycount_days
Spain8
Italy4
UK3
France2
Germany1
Portugal1

Python实现代码

import pandas as pd

# 构造原始DataFrame
data = {
    'date': ['2022-02-01', '2022-02-02', '2022-02-01', '2022-02-03', '2022-02-03',
             '2022-02-04', '2022-02-04', '2022-02-05', '2022-02-04', '2022-02-04'],
    'days': [1, 2, 3, 2, 1, 1, 1, 2, 5, 1],
    'country': ['Spain', 'Spain', 'Italy', 'France', 'Germany', 'Italy', 'UK', 'UK', 'Spain', 'Portugal']
}
df = pd.DataFrame(data)

# 按国家分组求和并排序,提取目标数组
country_summary = df.groupby('country')['days'].sum().reset_index(name='count_days')
sorted_summary = country_summary.sort_values(by='count_days', ascending=False)
countries = sorted_summary['country'].tolist()

print(countries)
# 输出: ['Spain', 'Italy', 'UK', 'France', 'Germany', 'Portugal']

内容的提问来源于stack exchange,提问作者Carola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 05:05:20