📜  pandas 阅读 google sheet - Python (1)

📅  最后修改于: 2023-12-03 14:45:05.072000             🧑  作者: Mango

Pandas 阅读 Google Sheet - Python

如果您需要从 Google Sheet 中读取数据并在 Python 中进行分析和操作,则可以使用 Pandas 库。这个库提供了许多函数和方法,可以方便地获取和处理 Google Sheet 中的数据。

安装依赖

您需要安装以下依赖才能使用 Pandas 和 gspread 库:

!pip install pandas gspread gspread_dataframe oauth2client
认证

要从 Google Sheet 中读取数据,您需要使用 Google API 和 OAuth2.0 进行身份验证。请参考以下步骤进行认证:

  1. 前往 Google Cloud Console;
  2. 创建一个项目并为其命名
  3. 然后从 API 和服务中激活 Google Sheets API
  4. 点击“创建凭据”来创建一个新的 OAuth 2.0 凭据
  5. 在“应用程序类型”下拉菜单中选择“其他”。
  6. 输入凭据名称并单击“创建”
  7. 单击“下载”以获取 JSON 凭据
获取工作表

在使用 Pandas 读取 Google Sheet 数据之前,您需要获取到工作表。

import gspread
from oauth2client.service_account import ServiceAccountCredentials

# 授权访问 google API
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', scope)
client = gspread.authorize(creds)

# 设置工作表
sheet = client.open('my_google_sheet').sheet1
使用 Pandas 读取 Google Sheet

现在您可以使用 Pandas 读取您的 Google Sheet 并将其转换为数据帧。

import pandas as pd

# 获取数据列表
data = sheet.get_all_values()

# 将数据列表转换成数据帧
df = pd.DataFrame(data)

# 设置数据帧列头
df.columns = df.iloc[0]
df = df[1:]

# 显示前 5 行数据
print(df.head())
将 Pandas 数据帧写入 Google Sheet

您可以使用 Pandas 将数据帧写入 Google Sheet。

import gspread_dataframe as gd

# 将数据帧写入工作表
gd.set_with_dataframe(sheet, df)

这是 Pandas 阅读 Google Sheet 的基本示例,您可以根据您的需求对其进行自定义,以便更好地适应您的需求。