【问题标题】:Merging empty pandas DF with rows from separate DF on Google Sheets将空的 pandas DF 与 Google 表格上单独 DF 的行合并
【发布时间】:2025-12-18 02:15:02
【问题描述】:

我正在使用此 Google 表格工作表 (https://docs.google.com/spreadsheets/d/1I2VIGfJOyod-13Fke8Prn8IkhpgZWbirPBbosm8EFCc/edit?usp=sharing) 我想创建一个类似的数据框,它只包含最后包含“OOO”的单元格(为了清楚起见,我用黄色突出显示了它们)。作为一个例子,这是我想从中得到的一个小sn-p: (https://docs.google.com/spreadsheets/d/1rRWgESE7kPTvchOL0RxEcqjEnY9oUsiMnov-qagHg7I/edit?usp=sharing)

基本上我想在这里创建自己的“时间表”。

import os
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
from googleapiclient import discovery


DATA_DIR = '/path/here/'
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive',
         'https://www.googleapis.com/auth/spreadsheets']
path = os.path.join(DATA_DIR, 'client_secret.json')
credentials = ServiceAccountCredentials.from_json_keyfile_name(path, scope)
client = gspread.authorize(credentials)
service = discovery.build('sheets', 'v4', credentials=credentials)
spreadsheet_id = 'Dcon19'

debug = False

spreadsheet = client.open(spreadsheet_id).sheet1
data = spreadsheet.get_all_values()
index = str(data[0][0])
headers = data.pop(0)
df_index = []

def conv_pd_df():

    df = pd.DataFrame(data, columns=headers, index=None)
    df = df.set_index(index)
    df_index.append(df.index.values)

    mask = df.applymap(lambda x: key in str(x))
    df1 = df[mask.any(axis=1)]

    return df1


def highlight(df1):
    df2 = pd.DataFrame(columns=headers[1:], index=df_index) # blank dataframe
    df2 = df2.fillna('none', inplace=True)
    for col in df1: 
        update_row = df1[df1[col].str.contains("OOO")]
        if not update_row.empty:
            try:
                df2.update(update_row, overwrite=True)
            except AttributeError as e:
                print(f'Error {e}')
    df2.to_csv('/path/dcon.csv', header=True)


if __name__ == '__main__':
    if not debug:
        df1 = conv_pd_df()
        highlight(df1)

现在我唯一返回的 df2 是一个空白数据框,因为当我尝试保存生成的 df2 时出现错误 AttributeError: 'NoneType' object has no attribute 'to_csv'

有谁知道如何使这项工作发挥作用,或更有效的方式来完成这项工作?

这是我的第一个真正的个人项目,因此我们将不胜感激!

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您引用的错误是因为您使用fillna 的方式。 df2.fillna('none', inplace=True) 将返回 None,这是您在尝试发送 df2.to_csv... 时看到的错误

    为你的高亮功能尝试这样的事情。

    def highlight(df1):
        df2 = pd.DataFrame(columns=headers[1:], index=df_index) # blank dataframe
        df2.fillna('none', inplace=True)
        for col in df1: 
            update_row = df1[df1[col].str.contains("OOO")]
            if not update_row.empty:
                try:
                    df2.update(update_row, overwrite=True)
                except AttributeError as e:
                    print(f'Error {e}')
        df2.to_csv('/path/dcon.csv', header=True)
    

    【讨论】:

      最近更新 更多