使用for循环进行格式化时出现ValueError:值的长度与索引的长度不匹配

2024-04-29 08:15:54 发布

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

我正在使用以下代码:

string="Verificamos {} vem crescendo em media {} porcento ao ano. A empresa {} por exemplo {}"
df['go']=[string.format(*r) for r in dfcres[['CNAE_x','Crescimento_t11_Peers_CNAE','Top_Cres1','Top_Cres1%']].values.tolist()]

如果我打印dfcres[['CNAE_x','Crescimento_t11_Peers_CNAE','Top_Cres1','Top_Cres1%']],我得到:

^{pr2}$

所以,df['go']应该是这样的:

  go
6 "Verificamos bovinos vem crescendo em media 0.10 porcento ao ano. A empresa Maria Ltd por exemplo 0.22"
8 "Verificamos suínos vem crescendo em media 0.08 porcento ao ano. A empresa Carla Ltd por exemplo 0.10"
9 "Verificamos construção vem crescendo em media 0.93 porcento ao ano. A empresa Maria Ltda por exemplo 0.30"

我得到了这个错误:

ValueError: Length of values does not match length of index

我不知道这个错误是什么意思。有人能帮助或建议另一种方法来获得同样的结果吗?在


Tags: gostringtopmediaemporanocnae
2条回答

我在自己的计算机上尝试了这个方法,没有使用dfcres,只是将值作为一个列表保存。这起作用了。所以,我怀疑问题在于:

  1. 你很可能在前面失踪了{}。(您的预期结果以数字开头),或
  2. 两个括号而不是一个,或者
  3. values()函数返回多少个值

试着从那里走

你的python版本是什么?在这个例子中,Python使用Python可以工作:

      CNAE_x  Outravar1   Crescimento_t11_Peers_CNAE    Top_Cres1   Top_Cres1% Outravar2
   "bovinos"         12                         0.10  "Maria Ltd"         0.22    "vaca"
    "suínos"       1575                         0.08  "Carla Ltd"         0.10   "porco"
"construção"        358                         0.93    "Mark SA"         0.30   "casas"

和编码:

^{pr2}$

但是如果df的行数与dfcresc不同,例如

>>> df
    CNAE_x  Outravar1   Crescimento_t11_Peers_CNAE  Top_Cres1   Top_Cres1%  Outravar2
0   bovinos       12                        0.10    Maria Ltd   0.22     vaca
1   construção   358                        0.93    Mark SA     0.30    casas

那么你仍然会得到这个错误的消息。在

如果不确定两个数据帧是否具有相同的行数,则应避免使用此方法。在

如果我的猜测是正确的,df是巴西经济活动(CNAE)的一个数据框架。因此,您可以使用CNAE_x作为唯一标识符,例如:

首先,创建列dfcres['go']

dfcres['go']=[string.format(*r) for r in dfcres.loc[,'CNAE_x','Crescimento_t11_Peers_CNAE','Top_Cres1','Top_Cres1%']].values.tolist()]

然后使用相同的CNAE_x值连接数据匹配行:

pd.merge(df, dfcres,
    how='right', on='CNAE_x')

相关问题 更多 >