gpt4 book ai didi

python - 使用 PyDrive 将 Pandas DataFrame 作为 Excel 文件直接上传到 Google Drive

转载 作者:太空狗 更新时间:2023-10-30 01:32:13 27 4
gpt4 key购买 nike

我正在尝试将 pandas.DataFrame 直接写入 Google 云端硬盘,而不是先在本地写入文件。我找不到解决方案,也不确定是否可行。我已经尝试了下面的代码,但我得到了一个 AttributeError

import pandas as pd
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LoadCredentialsFile(mycreds)
drive = GoogleDrive(gauth)

df = pd.DataFrame({'a':[1,2],'b':[2,3]})

f = drive.CreateFile({'id': '0B_6_uVX9biFuX0FJWFkt'}) #test.xlsx file
f.SetContentString(df)
f.Upload()

AttributeError: 'DataFrame' object has no attribute 'encode'

最佳答案

可以让 pandas 将 Excel 文件直接写入如下字符串:

代码:

wb = Workbook()
writer = pd.ExcelWriter('', engine='openpyxl')
writer.book = wb
df.to_excel(writer)
file_as_string = save_virtual_workbook(wb)

完整代码:

这是上面的代码结合你的例子。请注意,这部分未经测试。

import pandas as pd
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LoadCredentialsFile(mycreds)
drive = GoogleDrive(gauth)

df = pd.DataFrame({'a': [1, 2], 'b': [2, 3]})

from openpyxl.workbook import Workbook
from openpyxl.writer.excel import save_virtual_workbook

wb = Workbook()
writer = pd.ExcelWriter('', engine='openpyxl')
writer.book = wb
df.to_excel(writer)

f = drive.CreateFile({'id': '0B_6_uVX9biFuX0FJWFkt'}) #test.xlsx file
f.SetContentString(save_virtual_workbook(wb))
f.Upload()

关于python - 使用 PyDrive 将 Pandas DataFrame 作为 Excel 文件直接上传到 Google Drive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44445063/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com