gspread 列表选择列的列表

gspread list of list of a selection of columns

我有一个 google 传播sheet 像这样

A    B    C    D
0    1    2    3
4    5         7
8    9    8    7
6    5         3

我可以获取所有这些值作为列表的列表并将它们保存在 DataFrame 中,如下所示:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd


scope=['my_scope']

credentials = ServiceAccountCredentials.from_json_keyfile_name('my_credentials', scope)

gc = gspread.authorize(credentials)

GsheetName = 'here_the_name_of_my_spreadsheet'
workSheetName = 'here_the_wsheet_name'

sht = gc.open(GsheetName)
wks = sht.worksheet(workSheetName)

get_values = wks.get_all_values()

df= pd.DataFrame(get_values)

所以 df 是

   0    1    2    3
0  A    B    C    D
1  0    1    2    3
2  4    5    nan  7
3  8    9    8    7
4  6    5    nan  3

我也想这样做,但只选择单元格为空且具有 NAN 值的列 B 和 D,就像这样

   0    1    
0  B    C    
1  1    2    
2  5    nan     
3  9    8    
4  5    nan     

不操纵df怎么办?我想直接从 spreadsheet.

的值创建它

get_all_values() 方法获取所有 sheet 的值,但我只需要一些列和行,但我没有找到如何使用此方法或其他方法定义范围图书馆的 gspread 允许这样做。

  • 您想使用 gspread 直接从 "B:C" 检索值,如下所示。

    Input values: Values on Spreadsheet
    A    B    C    D
    0    1    2    3
    4    5         7
    8    9    8    7
    6    5         3
    
    Output values: Values you want to retrieve
       0     1
    0  1     2
    1  5  None
    2  9     8
    3  5  None
    
  • 在你的问题中,你说的是only selecting columns B and D with NAN values where the cell is empty。但是您的输出值似乎是 "B" 和 "C" 列中的值。所以我修改为从列 "B" 和 "C".

  • 中检索值

如果我的理解是正确的,这个修改怎么样?

发件人:

get_values = wks.get_all_values()

收件人:

get_values = sht.values_get(range=workSheetName + '!B:C')['values']

注:

  • 如果您不在脚本中使用 wks,您可以删除 wks = sht.worksheet(workSheetName)

参考:

如果我误解了你的问题,这不是你想要的结果,我深表歉意。