簡體   English   中英

從 URL 與 Z251D2BBFE9A3B95E56AZ91CEB30DC?6

[英]Reading only .csv file within a .zip from URL with Pandas?

There is a.csv file contained within a.zip file from a URL I am trying to read into a Pandas DataFrame; 我不想將 .zip 文件下載到磁盤,而是直接從 URL 讀取數據。 我意識到 pandas.read_csv() 只有在 .csv 文件是 .zip 中包含的唯一文件時才能執行此操作,但是,當我運行此文件時:

import pandas as pd

# specify zipped comma-separated values url
zip_csv_url = 'http://www12.statcan.gc.ca/census-recensement/2016/geo/ref/gaf/files-fichiers/2016_92-151_XBB_csv.zip'
df1 = pd.read_csv(zip_csv_url)

我明白了:

ValueError: Multiple files found in compressed zip file ['2016_92-151_XBB.csv', '92-151-g2016001-eng.pdf', '92-151-g2016001-fra.pdf']

.zip 的內容出現排列成列表; I'm wondering how I can assign the new DataFrame (df1) as the only available.csv file in the.zip (as the.zip file from the URL I will be using would only ever have one.csv file within it). 謝謝!

注意

當我運行此代碼時,來自帶有 shapefile 的單獨 URL 的相應 .zip 文件讀取 geopandas.read_file() 沒有問題:

import geopandas as gpd

# specify zipped shapefile url
zip_shp_url = 'http://www12.statcan.gc.ca/census-recensement/2011/geo/bound-limit/files-fichiers/2016/ldb_000b16a_e.zip'
gdf1 = gpd.read_file(zip_shp_url)

盡管.pdf文件也包含在.zip中,如下圖所示:

在此處輸入圖像描述

看起來 geopandas.read_file() 只能讀取創建 GeoDataFrame 所需的 shapefile,而忽略不必要的數據文件。 由於它基於 Pandas,Pandas 不應該也具有僅讀取 a.csv 中的 a.csv 的功能嗎? 有什么想法嗎?

import zipfile
import pandas as pd
from io import BytesIO
from urllib.request import urlopen


resp = urlopen(  YOUR_ZIP_LINK  )
files_zip = zipfile.ZipFile(BytesIO(resp.read()))
# files_zip.namelist()
directory_to_extract_to = YOUR_DESTINATION_FOLDER
file = YOUR_csv_FILE_NAME
with files_zip as zip_ref:
    zip_ref.extract(file,directory_to_extract_to)
pd.read_csv(directory_to_extract_to + file) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM