如何将Google Sheet导入Pandas DataFrame?需Anaconda模块及免CSV更新方案
所需Anaconda模块及快速配置指引
嘿,我来帮你搞定这个需求!要在Anaconda环境里直接用Pandas分析Google Sheet,还不用每次手动下载CSV就能自动拉取最新数据,你需要安装以下几个关键模块:
必装模块清单
pandas:不用说,这是你做数据分析的核心工具,Anaconda默认可能已经预装了,但如果没有的话还是得装上gspread:专门用于和Google Sheets API交互的Python库,能直接读写你的在线表格gspread-dataframe:把gspread和pandas打通的工具,能一键把Sheet里的数据转换成Pandas DataFrame,反过来也能把分析后的DataFrame写回Sheetgoogle-auth、google-auth-oauthlib、google-auth-httplib2:这三个是处理Google API身份认证的核心包,用来获取访问你的Google Sheet的权限,缺一不可
安装命令(Anaconda环境下)
优先用conda-forge源安装,这样能更好地兼容Anaconda环境:
conda install -c conda-forge pandas gspread gspread-dataframe google-auth google-auth-oauthlib google-auth-httplib2
如果某些包在conda源里找不到,就切换到pip安装(确保你已经激活了目标Anaconda环境):
pip install pandas gspread gspread-dataframe google-auth google-auth-oauthlib google-auth-httplib2
快速配置提示
装完包后,你还需要做两步简单的配置才能访问你的Sheet:
- 去Google Cloud Console创建一个新项目,启用Google Sheets API
- 创建一个服务账号,下载JSON格式的密钥文件,把它放到你的代码目录里
- 在Google Sheet里把服务账号的邮箱添加为协作者(给只读权限就够了,如果你不需要写回数据的话)
之后你就能用类似下面的代码自动拉取最新数据了:
import pandas as pd import gspread from google.oauth2.service_account import Credentials # 定义访问权限范围(只读的话用这个就够了) SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"] # 替换成你的服务账号密钥文件路径 creds = Credentials.from_service_account_file("your-service-key.json", scopes=SCOPES) client = gspread.authorize(creds) # 替换成你的Google Sheet ID和目标工作表名称 sheet_id = "your-google-sheet-id" worksheet = client.open_by_key(sheet_id).worksheet("Sheet1") # 一键把Sheet数据转成DataFrame df = pd.DataFrame(worksheet.get_all_records()) # 接下来就可以用Pandas做任何你想做的分析啦,每次运行都会拉取最新数据!
内容的提问来源于stack exchange,提问作者Manfred92
相关产品推荐
相关产品推荐

