将 CSV 从 Google Cloud 存储读取到 Pandas 数据框
- 2025-04-17 09:02:00
- admin 原创
- 16
问题描述:
我正在尝试将 Google Cloud Storage 存储桶中的 csv 文件读取到 panda 数据框中。
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
from io import BytesIO
from google.cloud import storage
storage_client = storage.Client()
bucket = storage_client.get_bucket('createbucket123')
blob = bucket.blob('my.csv')
path = "gs://createbucket123/my.csv"
df = pd.read_csv(path)
它显示此错误消息:
FileNotFoundError: File b'gs://createbucket123/my.csv' does not exist
我做错了什么,我找不到任何不涉及 google datalab 的解决方案?
解决方案 1:
更新
从 Pandas 0.24 版本开始,read_csv
支持直接从 Google Cloud Storage 读取数据。只需提供存储桶的链接,如下所示:
df = pd.read_csv('gs://bucket/your_path.csv')
然后将read_csv
使用gcsfs
模块来读取数据框,这意味着必须安装它(否则您将收到指向缺少依赖项的异常)。
为了完整起见,我留下了另外三个选项。
自制代码
粒细胞集落刺激因子
达斯克
我将在下文中介绍它们。
困难的方法:自己动手编写代码
我编写了一些便捷的函数来读取 Google 存储的数据。为了提高可读性,我添加了类型注解。如果您使用的是 Python 2,只需删除这些注解,代码即可正常运行。
假设您已获得授权,它对公共和私有数据集均有效。使用此方法,您无需先将数据下载到本地驱动器。
如何使用:
fileobj = get_byte_fileobj('my-project', 'my-bucket', 'my-path')
df = pd.read_csv(fileobj)
代码:
from io import BytesIO, StringIO
from google.cloud import storage
from google.oauth2 import service_account
def get_byte_fileobj(project: str,
bucket: str,
path: str,
service_account_credentials_path: str = None) -> BytesIO:
"""
Retrieve data from a given blob on Google Storage and pass it as a file object.
:param path: path within the bucket
:param project: name of the project
:param bucket_name: name of the bucket
:param service_account_credentials_path: path to credentials.
TIP: can be stored as env variable, e.g. os.getenv('GOOGLE_APPLICATION_CREDENTIALS_DSPLATFORM')
:return: file object (BytesIO)
"""
blob = _get_blob(bucket, path, project, service_account_credentials_path)
byte_stream = BytesIO()
blob.download_to_file(byte_stream)
byte_stream.seek(0)
return byte_stream
def get_bytestring(project: str,
bucket: str,
path: str,
service_account_credentials_path: str = None) -> bytes:
"""
Retrieve data from a given blob on Google Storage and pass it as a byte-string.
:param path: path within the bucket
:param project: name of the project
:param bucket_name: name of the bucket
:param service_account_credentials_path: path to credentials.
TIP: can be stored as env variable, e.g. os.getenv('GOOGLE_APPLICATION_CREDENTIALS_DSPLATFORM')
:return: byte-string (needs to be decoded)
"""
blob = _get_blob(bucket, path, project, service_account_credentials_path)
s = blob.download_as_string()
return s
def _get_blob(bucket_name, path, project, service_account_credentials_path):
credentials = service_account.Credentials.from_service_account_file(
service_account_credentials_path) if service_account_credentials_path else None
storage_client = storage.Client(project=project, credentials=credentials)
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(path)
return blob
粒细胞集落刺激因子
gcsfs是“用于 Google Cloud Storage 的 Pythonic 文件系统”。
如何使用:
import pandas as pd
import gcsfs
fs = gcsfs.GCSFileSystem(project='my-project')
with fs.open('bucket/path.csv') as f:
df = pd.read_csv(f)
达斯克
Dask “为分析提供了高级并行性,为您喜爱的工具提供大规模性能”。当您需要使用 Python 处理大量数据时,它非常有用。Dask 尝试模仿大部分pandas
API,使新手也能轻松上手。
这是read_csv
如何使用:
import dask.dataframe as dd
df = dd.read_csv('gs://bucket/data.csv')
df2 = dd.read_csv('gs://bucket/path/*.csv') # nice!
# df is now Dask dataframe, ready for distributed processing
# If you want to have the pandas version, simply:
df_pd = df.compute()
解决方案 2:
另一个选择是使用 TensorFlow,它具有从 Google Cloud Storage 进行流式读取的功能:
from tensorflow.python.lib.io import file_io
with file_io.FileIO('gs://bucket/file.csv', 'r') as f:
df = pd.read_csv(f)
使用 TensorFlow 还提供了一种便捷的方式来处理文件名中的通配符。例如:
将通配符 CSV 读入 Pandas
以下代码将把符合特定模式(例如:gs://bucket/some/dir/train-*)的所有 CSV 读取到 Pandas 数据框中:
import tensorflow as tf
from tensorflow.python.lib.io import file_io
import pandas as pd
def read_csv_file(filename):
with file_io.FileIO(filename, 'r') as f:
df = pd.read_csv(f, header=None, names=['col1', 'col2'])
return df
def read_csv_files(filename_pattern):
filenames = tf.io.gfile.Glob(filename_pattern)
dataframes = [read_csv_file(filename) for filename in filenames]
return pd.concat(dataframes)
用法
DATADIR='gs://my-bucket/some/dir'
traindf = read_csv_files(os.path.join(DATADIR, 'train-*'))
evaldf = read_csv_files(os.path.join(DATADIR, 'eval-*'))
解决方案 3:
我正在研究这个问题,不想费力地安装另一个库,gcsfs
文档中确实提到了This software is beta, use at your own risk
这一点……但我找到了一个很好的解决方法,想在这里发布一下,希望对其他人有帮助,它只使用 google.cloud 存储库和一些原生 Python 库。函数如下:
import pandas as pd
from google.cloud import storage
import os
import io
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'path/to/creds.json'
def gcp_csv_to_df(bucket_name, source_file_name):
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(source_blob_name)
data = blob.download_as_bytes()
df = pd.read_csv(io.BytesIO(data))
print(f'Pulled down file from bucket {bucket_name}, file name: {source_file_name}')
return df
此外,虽然这超出了这个问题的范围,但如果您想使用类似的功能将熊猫数据框上传到 GCP,下面是执行此操作的代码:
def df_to_gcp_csv(df, dest_bucket_name, dest_file_name):
storage_client = storage.Client()
bucket = storage_client.bucket(dest_bucket_name)
blob = bucket.blob(dest_file_name)
blob.upload_from_string(df.to_csv(), 'text/csv')
print(f'DataFrame uploaded to bucket {dest_bucket_name}, file name: {dest_file_name}')
希望这些功能对你有帮助!我知道我肯定会用到这些功能。
解决方案 4:
自 Pandas 1.2 以来,将文件从 Google 存储加载到 DataFrame 中变得非常容易。
如果您在本地机器上工作,它看起来像这样:
df = pd.read_csv('gcs://your-bucket/path/data.csv.gz',
storage_options={"token": "credentials.json"})
您从 Google 添加 credentials.json 文件作为令牌,这是导入的。
如果您在 Google Cloud 上工作,请执行以下操作:
df = pd.read_csv('gcs://your-bucket/path/data.csv.gz',
storage_options={"token": "cloud"})
解决方案 5:
如果您已安装,则pandas==0.24.0
本机支持此功能gcsfs
:https://github.com/pandas-dev/pandas/pull/22704。
在正式发布之前你可以尝试一下pip install pandas==0.24.0rc1
。
解决方案 6:
使用pandas和google-cloud-storage python 包:
首先,我们将文件上传到存储桶以获得完整工作的示例:
import pandas as pd
from sklearn.datasets import load_iris
dataset = load_iris()
data_df = pd.DataFrame(
dataset.data,
columns=dataset.feature_names)
data_df.head()
Out[1]:
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
3 4.6 3.1 1.5 0.2
4 5.0 3.6 1.4 0.2
将 csv 文件上传到存储桶(需要设置 GCP 凭据,请在此处阅读更多信息):
from io import StringIO
from google.cloud import storage
bucket_name = 'my-bucket-name' # Replace it with your own bucket name.
data_path = 'somepath/data.csv'
# Get Google Cloud client
client = storage.Client()
# Get bucket object
bucket = client.get_bucket(bucket_name)
# Get blob object (this is pointing to the data_path)
data_blob = bucket.blob(data_path)
# Upload a csv to google cloud storage
data_blob.upload_from_string(
data_df.to_csv(), 'text/csv')
现在我们在存储桶上有一个 csv,可以pd.read_csv
通过传递文件的内容来使用。
# Read from bucket
data_str = data_blob.download_as_text()
# Instanciate dataframe
data_dowloaded_df = pd.read_csv(StringIO(data_str))
data_dowloaded_df.head()
Out[2]:
Unnamed: 0 sepal length (cm) ... petal length (cm) petal width (cm)
0 0 5.1 ... 1.4 0.2
1 1 4.9 ... 1.4 0.2
2 2 4.7 ... 1.3 0.2
3 3 4.6 ... 1.5 0.2
4 4 5.0 ... 1.4 0.2
[5 rows x 5 columns]
比较这两种方法后pd.read_csv('gs://my-bucket/file.csv')
,我发现这里描述的方法更明确地说明了client = storage.Client()
身份验证的流程(这在使用多个凭据时非常方便)。此外,storage.Client
如果您在 Google Cloud Platform 的资源上运行此代码,它已经完全安装好了;如果pd.read_csv('gs://my-bucket/file.csv')
您要使用 Pandas 访问 Google Storage,则需要先安装gcsfs
允许 Pandas 访问 Google Storage 的软件包。
解决方案 7:
read_csv
不支持gs://
来自文档:
该字符串可以是 URL。有效的 URL 方案包括 http、ftp、s3 和 file。对于文件 URL,需要主机名。例如,本地文件可以是 file://localhost/path/to/table.csv
您可以下载文件或将其作为字符串获取以便对其进行操作。
解决方案 8:
有三种方式可以访问 GCS 中的文件:
下载客户端库(这个适合你)
在 Google Cloud Platform Console 中使用云存储浏览器
使用 gsutil,这是一个用于处理 Cloud Storage 中的文件的命令行工具。
按照步骤 1 的步骤,设置GSC 以完成您的工作。之后,您需要:
import cloudstorage as gcs
from google.appengine.api import app_identity
然后,您必须指定云存储桶名称并创建读/写函数来访问您的存储桶:
您可以在这里找到剩余的读/写教程:
解决方案 9:
Google Cloud 存储有一个方法download_as_bytes(),然后,您可以从字节 HT 读取 csv 到NEWBEDEV,代码如下所示:
import pandas as pd
from io import BytesIO
blob = storage_client.get_bucket(event['bucket']).get_blob(event['name'])
blobBytes = blob.download_as_bytes()
df = pd.read_csv(BytesIO(blobBytes))
我的event
来自云存储示例
解决方案 10:
import gcsfs
如果加载压缩文件,仍然需要使用。
pd.read_csv('gs://your-bucket/path/data.csv.gz')
在 pd.版本=> 0.25.3 中尝试,出现以下错误,
/opt/conda/anaconda/lib/python3.6/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds)
438 # See https://github.com/python/mypy/issues/1297
439 fp_or_buf, _, compression, should_close = get_filepath_or_buffer(
--> 440 filepath_or_buffer, encoding, compression
441 )
442 kwds["compression"] = compression
/opt/conda/anaconda/lib/python3.6/site-packages/pandas/io/common.py in get_filepath_or_buffer(filepath_or_buffer, encoding, compression, mode)
211
212 if is_gcs_url(filepath_or_buffer):
--> 213 from pandas.io import gcs
214
215 return gcs.get_filepath_or_buffer(
/opt/conda/anaconda/lib/python3.6/site-packages/pandas/io/gcs.py in <module>
3
4 gcsfs = import_optional_dependency(
----> 5 "gcsfs", extra="The gcsfs library is required to handle GCS files"
6 )
7
/opt/conda/anaconda/lib/python3.6/site-packages/pandas/compat/_optional.py in import_optional_dependency(name, extra, raise_on_missing, on_version)
91 except ImportError:
92 if raise_on_missing:
---> 93 raise ImportError(message.format(name=name, extra=extra)) from None
94 else:
95 return None
ImportError: Missing optional dependency 'gcsfs'. The gcsfs library is required to handle GCS files Use pip or conda to install gcsfs.
扫码咨询,免费领取项目管理大礼包!