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

2024-06-08 04:30:31 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我感兴趣的数据

http://fenixservices.fao.org/faostat/static/bulkdownloads/Production_Crops_E_All_Data.zip

它由3个文件组成:

enter image description here

我想下载带有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)

熊猫可以下载文件,可以使用拉链,当然也可以使用csv文件。但是,如何处理归档文件中的一个特定文件和多个文件

现在我发现了一个错误

ValueError:('在压缩zip文件%s中找到多个文件)

这篇文章没有回答我的问题,因为我在一个zip中有多个文件 Read a zipped file as a pandas DataFrame


Tags: 文件csv数据orgcropshttppandasdata
2条回答

From this link

编辑:将python3 StringIO更新为io.StringIO

编辑:更新了urllib的导入,将StringIO的用法更改为BytesIO。另外,您的CSV文件不是utf-8编码,我尝试了latin1,这很有效

试试这个

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')

希望这有帮助

您可以使用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中同样地工作;但是要注意的是,它的特征不如熊猫丰富;但它是一个强大且非常快速的工具

更新:您也可以使用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)

相关问题 更多 >

    热门问题