【问题标题】:Export dataframe as csv file from google colab to google drive将数据框作为 csv 文件从 google colab 导出到 google drive
【发布时间】:2019-05-22 18:07:51
【问题描述】:

我想将数据帧作为 csv 从 colab 上传到谷歌驱动器。我尝试了很多但没有运气。我可以上传简单的文本文件,但无法上传 csv。

我尝试了以下代码:

import pandas as pd
df=pd.DataFrame({1:[1,2,3]})
df.to_csv('abc',sep='\t')
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
uploaded = drive.CreateFile({'title': 'sample.csv', 'mimeType':'csv'})
uploaded.SetContentFile('abc')
uploaded.Upload()

【问题讨论】:

标签: python csv google-colaboratory drive


【解决方案1】:

使用 mount 代替 pydrive 可能更容易。

from google.colab import drive
drive.mount('drive')

身份验证后,您可以复制您的 csv 文件。

df.to_csv('data.csv')
!cp data.csv "drive/My Drive/"

【讨论】:

  • 谢谢,这很好用,我想知道 '!cp data.csv drive/My\ Drive/' 行有什么作用?
  • 它将data.csv从当前目录复制到你的gdrive(安装在drive/My Drive/)
  • 是否可以将文件复制到colab文件所在的文件夹中?
【解决方案2】:

如果您不想使用 Pandas,请执行以下操作:

df_mini.coalesce(1)\
   .write\
   .format('com.databricks.spark.csv')\
   .options(header='true', delimiter='\t')\
   .save('gdrive/My Drive/base_mini.csv')

【讨论】:

    【解决方案3】:

    不使用 !cp 命令

    from google.colab import drive

    • 将 google 驱动器安装到 Colab Notebook

    drive.mount('/drive')

    • 确保在上传之前在谷歌驱动器中创建文件夹名称

    df.to_csv('/drive/My Drive/folder_name/name_csv_file.csv')

    【讨论】:

      【解决方案4】:
      # Import Drive API and authenticate.
      from google.colab import drive
      
      # Mount your Drive to the Colab VM.
      drive.mount('/gdrive')
      
      # Write the DataFrame to CSV file.
      with open('/gdrive/My Drive/foo.csv', 'w') as f:
        df.to_csv(f)
      

      【讨论】:

        【解决方案5】:

        如果你想在本地保存,那么你可以使用这个

        f.to_csv('sample.csv')
        from google.colab import files
        files.download("sample.csv")
        

        【讨论】:

          【解决方案6】:

          其他答案几乎奏效了,但我需要稍作调整:

          from google.colab import drive
          drive.mount('drive')
          
          df.to_csv('/content/drive/My Drive/filename.csv', encoding='utf-8', index=False)
          

          /content/ 位被证明是必要的

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-08-19
            • 2017-05-08
            • 2018-10-22
            • 1970-01-01
            • 2023-04-04
            • 2021-02-24
            • 2022-08-20
            • 2021-02-14
            相关资源
            最近更新 更多