如何在python中修复“值的长度与索引不匹配”?

时间:2019-04-14 18:31:29

标签: python python-2.7

我一直在尝试从巴西的一家专营店获取地址列表,但是当我运行代码时,它将启动,运行两个城市,然后停止并出现“ ValueError”

我一直试图运行的代码是这样的:

import requests
import json
import pandas as pd

dMun = pd.read_json('https://servicodados.ibge.gov.br/api/v1/localidades/municipios')

dEndTotal = pd.DataFrame()
for iMun in range(len(dMun)):
    sCidade = dMun.loc[iMun,'nome']
    print(str(iMun) + ' - '+ dMun.loc[iMun,'nome'])
    sSigla = dMun.loc[iMun,'microrregiao']['mesorregiao']['UF']['sigla']
    r = requests.post('https://www.5asec.com.br/busca-lojas-endereco', data = {'endereco':'A, 1 {}/{}'.format(sCidade,sSigla)})
    jEnd = json.loads(r.text)
    dEnd = pd.DataFrame.from_records(jEnd['lojas'])
    print(dEnd)
    if len(dEnd) > 0:
        for sChave in jEnd['lojas'][0]['Endereco'].keys():
            dEnd[sChave] = []

        for i in range(len(dEnd)):
            for sChave in jEnd['lojas'][i]['Endereco'].keys():
                dEnd[sChave][i] = jEnd['lojas'][i]['Endereco'][sChave]
        dEndTotal = pd.concat([dEndTotal,dEnd],ignore_index=False).drop_duplicates().reset_index(drop=True)

但是导致此错误的原因:

0 - Alta Floresta D'Oeste
Empty DataFrame
Columns: []
Index: []
1 - Ariquemes
        CEP  Codigo CodigoExterno  ...  Telefone  TemEcommerce        Url
0  76870512     675        69004P  ...  35366864         False  ariquemes

[1 rows x 16 columns]
Traceback (most recent call last):

  File "<ipython-input-1-cd9a35514f7e>", line 1, in <module>
    runfile('C:/Users/vinis/OneDrive/Área de Trabalho/5aSec.py', wdir='C:/Users/vinis/OneDrive/Área de Trabalho')

  File "C:\Users\vinis\Anaconda2\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 786, in runfile
    execfile(filename, namespace)

  File "C:\Users\vinis\Anaconda2\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 95, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "C:/Users/vinis/OneDrive/Área de Trabalho/5aSec.py", line 38, in <module>

  File "C:\Users\vinis\Anaconda2\lib\site-packages\pandas\core\frame.py", line 3370, in __setitem__
    self._set_item(key, value)

  File "C:\Users\vinis\Anaconda2\lib\site-packages\pandas\core\frame.py", line 3445, in _set_item
    value = self._sanitize_column(key, value)

  File "C:\Users\vinis\Anaconda2\lib\site-packages\pandas\core\frame.py", line 3630, in _sanitize_column
    value = sanitize_index(value, self.index, copy=False)

  File "C:\Users\vinis\Anaconda2\lib\site-packages\pandas\core\internals\construction.py", line 519, in sanitize_index
    raise ValueError('Length of values does not match length of index')

ValueError: Length of values does not match length of index

我该如何解决这个问题? 谢谢大家的帮助

很抱歉,如果帖子不全正确

0 个答案:

没有答案