You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas使用.loc按索引赋值出现ValueError长度不匹配错误如何解决?

报错原因

你代码中待赋值的左侧 df1.loc[df_state_group.index, 'assigned_airport'] 对应4行数据,而右侧 df_airports.loc[index_nearest_airport,'airports'].values 是长度为1的数组,二者长度不匹配,因此触发ValueError: Must have equal len keys and value when setting with an iterable报错。

解决方案

以下三种方案均可解决问题,优先推荐第一种最简方案:

  • 方案1:提取标量直接赋值
    由于你需要给4行赋同一个值,直接把右侧的数组转为标量即可:
    df1.loc[df_state_group.index, 'assigned_airport'] = df_airports.loc[index_nearest_airport,'airports'].values[0]
    
  • 方案2:扩展右侧值长度与左侧匹配
    该方案也适用于后续多值匹配多行的场景,当前场景下将长度为1的机场值重复4次即可:
    import numpy as np
    airport_val = df_airports.loc[index_nearest_airport,'airports'].values
    df1.loc[df_state_group.index, 'assigned_airport'] = np.repeat(airport_val, len(df_state_group))
    
  • 方案3:直接定位机场标量值
    已知需要取df_airports索引3的airports字段值,可直接提取标量赋值:
    df1.loc[df_state_group.index, 'assigned_airport'] = df_airports.loc[3, 'airports']
    

内容的提问来源于stack exchange,提问作者Moe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 13:06:02