【问题标题】:Create Dataframe from a csv inside a zip file从 zip 文件中的 csv 创建 Dataframe
【发布时间】:2018-11-07 09:36:23
【问题描述】:

我正在尝试读取 pandas 数据框中的 WGIData.csv 文件。 WGIData.csv 存在于我从该 url 下载的 zip 文件中

http://databank.worldbank.org/data/download/WGI_csv.zip

但是当我尝试阅读时,它会抛出错误 BadZipFile: File is not a zip file

这是我的python代码

import pandas as pd
from urllib.request import urlopen
from zipfile import ZipFile

class Get_Data():

    def Return_csv_from_zip(self, url):
        self.zip = urlopen(url)
        self.myzip = ZipFile(self.zip)
        self.myzip = self.zip.extractall(self.myzip)
        self.file = pd.read_csv(self.myzip)
        self.zip.close()

        return self.file

url = 'http://databank.worldbank.org/data/download/WGI_csv.zip'
data = Get_Data()
df = data.Return_csv_from_zip(url)

【问题讨论】:

  • 您的 zip 有两个文件:['WGIData.csv', 'WGISeries.csv'] 这可能是问题所在。
  • 这个 zip 文件还不错,我用 winrar @AChampion 解压了
  • 那我该怎么办?@coldspeed
  • 我只想阅读 WGIData.csv
  • 这样的事情可能会有所帮助:stackoverflow.com/q/21075999/4909087

标签: python pandas unzip zipfile


【解决方案1】:

urlopen() 不返回可以发送到ZipFile() 的对象 (HTTPResponse)。您可以read() 回复并使用io.BytesIO() 做您需要的事情:

In []:
from io import BytesIO

z = urlopen('http://databank.worldbank.org/data/download/WGI_csv.zip')
myzip = ZipFile(BytesIO(z.read())).extract('WGIData.csv')
pd.read_csv(myzip)

Out[]:
     Country Name Country Code                                     Indicator Name    Indicator Code       1996  \
0        Anguilla          AIA                    Control of Corruption: Estimate            CC.EST        NaN   
1        Anguilla          AIA           Control of Corruption: Number of Sources         CC.NO.SRC        NaN   
2        Anguilla          AIA             Control of Corruption: Percentile Rank        CC.PER.RNK        NaN   
3        Anguilla          AIA  Control of Corruption: Percentile Rank, Lower ...  CC.PER.RNK.LOWER        NaN   
4        Anguilla          AIA  Control of Corruption: Percentile Rank, Upper ...  CC.PER.RNK.UPPER        NaN   
5        Anguilla          AIA              Control of Corruption: Standard Error        CC.STD.ERR        NaN   
...

【讨论】:

  • 有没有不指定文件名的方法?
  • 您可以extractall() 提取压缩文件的所有内容,或者您​​可以获取namelist() 并遍历名称。
猜你喜欢
  • 2012-08-28
  • 2017-10-04
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 2016-03-04
  • 2016-09-23
  • 2021-08-19
  • 2021-12-08
相关资源
最近更新 更多