← 返回题库
初级

统计消费分类金额分布

未完成
初级参考 完整示例代码供参考,建议自己理解后重新输入
def solve():
    from pyodide.http import open_url
    from io import StringIO
    import pandas as pd
    txs = pd.read_csv(StringIO(open_url("https://data.zuihe.com/dbd/ms-ledger/state_02/transactions.csv").read()))
    cats = pd.read_csv(StringIO(open_url("https://data.zuihe.com/dbd/ms-ledger/state_00/categories.csv").read()))
    by_cat = txs.groupby('category_id').agg(amount=('amount','sum'),count=('tx_id','count')).reset_index()
    by_cat = by_cat.merge(cats[['category_id','name']], on='category_id', how='left').sort_values('amount',ascending=False)
    total = by_cat['amount'].sum()
    print("Spending by category:")
    for _, row in by_cat.iterrows():
        pct = round(row['amount']/total*100,1)
        print(f"  {str(row['name']):<10}: {round(row['amount'],2):>8} CNY {pct}%")

示例

输入
solve()
期望输出
Spending by category:
  交通出行      :  6843.64 CNY 11.6%
  咖啡奶茶      :  6245.04 CNY 10.6%
  网购        :  5725.29 CNY 9.7%
  家居日用      :  5384.94 CNY 9.1%
  服装        :  4980.52 CNY 8.4%
  餐饮        :  4581.45 CNY 7.8%
  娱乐        :   4056.2 CNY 6.9%
  旅行住宿      :  3170.76 CNY 5.4%
  游戏充值      :  2551.86 CNY 4.3%
  医疗健康      :  2430.73 CNY 4.1%
  超市生鲜      :  2413.06 CNY 4.1%
  运动健身      :  2387.51 CNY 4.0%
  数码电子      :  2192.82 CNY 3.7%
  金融保险      :  1822.76 CNY 3.1%
  教育培训      :  1587.91 CNY 2.7%
  美容护理      :  1150.73 CNY 2.0%
  住房水电      :   898.73 CNY 1.5%
  其他        :   276.71 CNY 0.5%
  宠物        :   193.58 CNY 0.3%
  礼品        :    96.17 CNY 0.2%
Python 代码 🔒 登录后使用
🔒

登录后即可练习

注册免费账号,在浏览器中直接运行 Python 代码