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

Python 使用pandas从zip读取特定的csv文件,python,pandas,Python,Pandas,这是我感兴趣的数据 它由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) 熊猫可以下载文件,可以使用拉链,当然也

这是我感兴趣的数据

它由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)
熊猫可以下载文件,可以使用拉链,当然也可以使用csv文件。但是,如何处理归档文件中的一个特定文件和多个文件

现在我发现了一个错误

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

这篇文章没有回答我的问题,因为我在一个zip中有多个文件

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

更新:您也可以使用该模块:

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)

编辑:将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')

希望这有帮助

这回答了你的问题吗?遗憾的是,我不能使用pip安装来安装这个库。SturtExe:不可确定合适的C++编译器。请指定一个编译器在“代码> CXX/COD>环境变量中可执行”。“导入URLLIB应该被编辑以导入URLLI.Realest.Field= zip文件(IO。StringIO(R))回溯:Type Error:RealalAlgIt值必须是STR或NOR,not ByTest感谢您更新帖子,但错误“TypeError:初始值必须为str或None,而不是bytes”仍然存在。//。read().decode('utf8')没有帮助hey@IgorK.Updated的答案解决了这个问题,请使用BytesIO而不是StringIO干杯!