# %% [python] cell-ae508cef942a
import pyodide, os, requests, js, json, micropip, pandas as pd
await micropip.install('shuyouqi-0.0.0-py3-none-any.whl')
await micropip.install('et_xmlfile-2.0.0-py3-none-any.whl')
from shuyouqi import profiling
await micropip.install('openpyxl-3.1.5-py2.py3-none-any.whl')
# %% [plaintext] cell-9ba6fcad55b1
《各国人口数据示例》
Country Name,1960,1961,1962,1963
Aruba,54922,55578,56320,57002
Africa Eastern and Southern,130072080,133534923,137171659,140945536
Afghanistan,9035043,9214083,9404406,9604487
Africa Western and Central,97630925,99706674,101854756,104089175
# %% [prompt] cell-3bd85190e2a9
我需要从pyodide文件系统的根目录加载一个名为population.csv的CSV文件。该文件包含从1960年到2023年各国的人口数据,其中第一列是国家名称(Country Name)、其它每一列都是具体年份的各国人口数量。表格示例参看《资料》。请生成相应的代码,使用pandas库读取这个CSV文件,并将其存储到一个名为df的DataFrame中。
# %% [python] cell-cca0c96ebdd1
import pandas as pd

# 从pyodide的根文件系统读取CSV文件
df = pd.read_csv('/population.csv')
# %% [prompt] cell-7b5c9515fb78
已经成功加载了人口数据(参看《各国人口数据示例》)到DataFrame df中。现在,我需要将数据进行透视处理,将年份作为独立的列(列名为Year),同时保留Country Name列。此外,我还需要将Year列的数据类型转换为整数。请生成相应的代码,使用pandas库来完成这一任务,并将处理后的数据存储回一个名为df2的DataFrame中。
# %% [python] cell-047c3af109f3
import pandas as pd

# 使用melt将年份列转换为行,生成长格式数据
df2 = df.melt(id_vars=['Country Name'], var_name='Year', value_name='Value')

# 将Year列转换为整数类型
df2['Year'] = df2['Year'].astype(int)
print(df2)
# %% [prompt] cell-27d1be78269d
我已经完成了人口数据的加载和预处理。现在,我想使用VegaLite语言绘制一个折线图,展示从1960年到2023年所有国家和大洲的人口趋势线。x轴表示年份(Year),y轴表示人口数量(Population),并根据国家或大洲名称(Country Name)进行颜色区分。请生成相应的VegaLite JSON代码。
# %% [vegalite] cell-ea9011227c53
{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "全球人口趋势(1960-2023)",
  "width": 800,
  "height": 500,
  "data": {
    "values":  "df2"// 您的实际数据应替换此处    
  },
  "mark": {
    "type": "line",
    "strokeWidth": 1.5,
    "tooltip": true
  },
  "encoding": {
    "x": {
      "field": "Year",
      "type": "quantitative",
      "axis": {"title": "年份", "labelFlush": false}
    },
    "y": {
      "field": "Value",
      "type": "quantitative",
      "title": "人口数量",
      "axis": {"format": "~s"} // 自动转换为百万/十亿单位
    },
    "color": {
      "field": "Country Name",
      "type": "nominal",
      "title": "国家/大洲",
      "scale": {"scheme": "category20"} // 使用20色分类调色板
    }
  },
  "config": {
    "view": {"stroke": "transparent"},
    "legend": {
      "columns": 2,
      "symbolType": "stroke",
      "title": null
    }
  }
}