我在 Amazon Cloud 的 S3 存储桶中有几个 CSV 文件 (50 GB)。我正在尝试使用以下代码在 Jupyter Notebook(使用 Python3 内核)中读取这些文件:
import boto3
from boto3 import session
import pandas as pd
session = boto3.session.Session(region_name='XXXX')
s3client = session.client('s3', config = boto3.session.Config(signature_version='XXXX'))
response = s3client.get_object(Bucket='myBucket', Key='myKey')
names = ['id','origin','name']
dataset = pd.read_csv(response['Body'], names=names)
dataset.head()
但是当我运行代码时遇到以下错误:
valueError:无效的文件路径或缓冲区对象类型:class 'botocore.response.StreamingBody'
我遇到了这个 bug report关于 pandas 和 boto3 对象还不兼容。
我的问题是,我还能如何将这些 CSV 文件从我的 S3 存储桶导入到我在云端运行的 Jupyter Notebook。
最佳答案
您还可以使用 s3fs,它允许 pandas 直接从 S3 读取:
import s3fs
# csv file
df = pd.read_csv('s3://{bucket_name}/{path_to_file}')
# parquet file
df = pd.read_parquet('s3://{bucket_name}/{path_to_file}')
然后,如果您的存储桶中有多个文件,您可以像这样遍历它们:
import boto3
s3_resource = boto3.resource('s3')
bucket = s3_resource.Bucket(name='{bucket_name}')
for file in bucket.objects.all():
# do what you want with the files
# for example:
if 'filter' in file.key:
print(file.key)
new_df = pd.read_csv('s3:://{bucket_name}/{}'.format(file.key))
关于python - 从 S3 将 CSV 数据加载到 Jupyter Notebook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48564598/