# %%--- [python] cell-f74e05782eef # properties: # run_on_load: true # ---%% print("开始初始化数据分析和可视化的运行环境,请稍候……") import micropip await micropip.install("/pypi/openpyxl-3.1.5-py2.py3-none-any.whl") await micropip.install("/pypi/pyfonts-0.0.2-py3-none-any.whl") import pandas as pd import pyodide from pyfonts import load_font # 字体文件的URL file_url = '/assets/fonts/NotoSansSC-Regular.ttf' # 请将此URL替换为实际文件的URL # 内存中保存路径 local_file_path = '/NotoSansSC-Regular.ttf' # 下载文件并保存到本地 try: response = await pyodide.http.pyfetch(file_url) # Return the response body as a bytes object image_data = await response.bytes() with open(local_file_path, 'wb') as f: f.write(image_data) print(f"中文字体已成功下载并保存为: {local_file_path}") except Exception as e: print(f"下载文件时出错: {e}") font = load_font(font_path="/NotoSansSC-Regular.ttf") print("数据分析和可视化的运行环境已经就绪。可以进行第1步了。") # %% [markdown] cell-5e351e7966a3 ## 第1步:请从本地上传一个用电商记插件采集的淘宝搜索2025新版结果(含综合排序和销量排序)的Excel文件。[下载示例](https://www.dianshangji.cn/u/user5344/cfiles/download/43a1d213-1bc8-43ac-8979-c0715630af3b) # %%--- [html] cell-a5b79fdf3c10 # properties: # run_on_load: true # ---%% <input class="btn btn-primary" type="file" id="fileInput"/> # %%--- [javascript] cell-d28877a258f5 # properties: # run_on_load: true # ---%% const fileInput = document.getElementById('fileInput'); fileInput.addEventListener('change', async function(ev){ const file = fileInput.files[0]; if (!file) { alert("Please select a file first."); return; } // 读取文件为 ArrayBuffer const arrayBuffer = await file.arrayBuffer(); // 将 ArrayBuffer 转换为 Uint8Array const uint8Array = new Uint8Array(arrayBuffer); pyodide.FS.writeFile('/file1.xlsx', uint8Array); }); # %% [markdown] cell-21815780a840 ## 第2步:点击运行下面这个单元格,先处理“月销量”字段的数据,然后绘制“价格-月销量”散点图。 # %% [python] cell-2d6e920188c2 print("开始读取内存中的Excel文件……") # 读取Excel文件,跳过前两行(即从第三行开始读取),只保留“价格”和“月销量”两个字段 df = pd.read_excel('/file1.xlsx', skiprows=2, usecols=['价格', '月销量']) # 打印前5条记录 print(df.head(5)) import pandas as pd import re # 定义一个函数来处理“月销量”字段 def clean_month_sales(sales_str): if pd.isna(sales_str): return None sales_str = str(sales_str).strip() if "本月行业热销" in sales_str: return 1000 elif "万+" in sales_str: match = re.search(r'(\d+)', sales_str) if match: return int(match.group(1)) * 10000 elif "+人收货" in sales_str: match = re.search(r'(\d+)', sales_str) if match: return int(match.group(1)) try: return int(sales_str) except ValueError: return None # 应用函数到“月销量”列 df['月销量'] = df['月销量'].apply(clean_month_sales) # 打印前5条记录以检查结果 print(df.head(5)) import matplotlib.pyplot as plt import numpy as np # 确保之前的数据框df已经存在并且包含"价格"和"月销量"列 # 如果数据框df不存在或需要重新加载,请确保在此之前执行相应的读取操作 # 过滤掉“价格”大为1000的记录 df_filtered = df[df['价格'].apply(lambda x: (1 <= x <= 1000))] # 绘制散点图 plt.figure(figsize=(10, 6)) plt.scatter(df_filtered['价格'], df_filtered['月销量'], alpha=0.5) plt.title('价格 vs 月销量 散点图', font=font) plt.xlabel('价格', font=font) plt.ylabel('月销量', font=font) plt.grid(True) plt.show() print("散点图绘制完毕。")