我正在尝试从一个大的谷歌表格中的特定表格中获取特定的列数据。 例如,我有一张床单清单
Sheets = ['Sheet 1', 'Sheet 2', 'Sheet 3']
从这些工作表中,我想检索特定的列,例如
Column_headers = ['A', 'B']
我现在正在做的是从中获取数据
import gspread
from gspread_dataframe import set_with_dataframe
import pandas as pd
pd.set_option("display.max_columns", None)
pd.set_option('display.max_rows', None)
sa = gspread.service_account(filename='file.json')
book = sa.open("book")
Sheets = ['Sheet 1', 'Sheet 2', 'Sheet 3']
Column_headers = ['A', 'B']
for i in Sheets:
2022_sheet = book.worksheet(i)
records = 2022_sheet.get_all_records()
data_2022 = zip(*(e for e in zip(*record) if e[0] in Column_headers))
getdata_2022 = pd.DataFrame(data_2022, columns = Column_headers)
print(getdata_2022)
我收到以下错误
GSpreadException: the given 'expected_headers' are not uniques
那是因为标题不是唯一的 (obv) 这就是我检索特定列的原因,而且我无法理解我循环遍历“工作表”以仅从特定工作表获取数据的位置。最终的结果应该是两列“A”和“B”,其中包含来自特定 3 张纸的所有数据。
IIUC 尝试做以下事情:
import gspread
import gspread_dataframe as gd
import pandas as pd
# connect to the service account
sa = gspread.service_account(filename='file.json')
# open the Google Sheet
book = sa.open("Social_Media_Analytics")
# The list of sheet names and columns that you want
Sheets = ['Sheet 1', 'Sheet 2', 'Sheet 3']
Column_headers = ['A', 'B']
# list comprehension using gd.get_as_dataframe to create a frame for each sheet
# then concat all frames together
df = pd.concat([gd.get_as_dataframe(book.worksheet(sheet))[Column_headers] for sheet in Sheets])