pandas 使用panda从zip读取特定的csv文件

kzipqqlq  于 2022-11-20  发布在  其他
关注(0)|答案(2)|浏览(220)

这里有一个我感兴趣的数据。
http://fenixservices.fao.org/faostat/static/bulkdownloads/Production_Crops_E_All_Data.zip
它由3个文件组成:

我想下载包含Pandas的zip文件,并从名为Production_Crops_E_All_Data.csv的文件创建数据框

import pandas as pd
url="http://fenixservices.fao.org/faostat/static/bulkdownloads/Production_Crops_E_All_Data.zip"
df=pd.read_csv(url)

Pandas可以下载文件,它可以与zips工作,当然它可以与csv文件工作。但我怎么能与1个特定的文件在存档与许多文件?
现在出现错误
ValueError:('在压缩的zip文件%s中找到多个文件)
这篇文章没有回答我的问题,因为我有多个文件在1 zip Read a zipped file as a pandas DataFrame

8yoxcaq7

8yoxcaq71#

From this link
试试这个

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

r = urlopen("http://fenixservices.fao.org/faostat/static/bulkdownloads/Production_Crops_E_All_Data.zip").read()
file = ZipFile(io.BytesIO(r))
data_df = pd.read_csv(file.open("Production_Crops_E_All_Data.csv"), encoding='latin1')
data_df_noflags = pd.read_csv(file.open("Production_Crops_E_All_Data_NOFLAG.csv"), encoding='latin1')
data_df_flags = pd.read_csv(file.open("Production_Crops_E_Flags.csv"), encoding='latin1')

希望这对你有帮助!编辑:将python3的StringIO更新为io.StringIO
编辑:更新了urllib的导入,将StringIO的用法改为BytesIO。另外,你的CSV文件不是UTF-8编码,我试过latin 1,效果很好。

voase2hg

voase2hg2#

你可以使用python的datatable,它是Rdatatable在python中的重新实现。
读入数据:

from datatable import fread

#The exact file to be extracted is known, simply append it to the zip name:
 url = "Production_Crops_E_All_Data.zip/Production_Crops_E_All_Data.csv"

 df = fread(url)

#convert to pandas

 df.to_pandas()

您同样可以在datatable中工作;然而,请注意,它不像Pandas那样功能丰富;但它是一个强大且非常快速工具。
更新:您也可以使用zipfile模块:

from zipfile import ZipFile
from io import BytesIO

with ZipFile(url) as myzip:
    with myzip.open("Production_Crops_E_All_Data.csv") as myfile:
        data = myfile.read()

#read data into pandas
#had to toy a bit with the encoding,
#thankfully it is a known issue on SO
#https://stackoverflow.com/a/51843284/7175713
df = pd.read_csv(BytesIO(data), encoding="iso-8859-1", low_memory=False)

相关问题