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

替换Pandas DataFrame空值时报错:NumPy布尔数组索引输入维度不符

问题描述

从API提取数据转换为Pandas DataFrame后,数据结构如下:

session_id            visitor_id                 server_time                  updated_at       referrer_type      device_type
0      316046440780942428  14256666432883430808  2023-03-01T22:18:13.515749  2023-03-01T22:18:16.000000   [1, Direct entry]  [1, Smartphone]
1     1559381029125193934   6223493451404765687  2023-03-01T22:18:12.466276  2023-03-01T22:18:16.000000  [2, Search engine]  [1, Smartphone]
2     1634055602528061570   3488177825412806861  2023-03-01T22:18:12.609022  2023-03-01T22:18:16.000000   [1, Direct entry]  [1, Smartphone]
3     2336103663959038531   8418933936834842610  2023-03-01T22:18:12.559650  2023-03-01T22:18:16.000000        [3, Website]     [0, Desktop]
4     3848276761860900650   8640986235790038067  2023-03-01T22:16:30.337437  2023-03-01T22:18:16.000000  [2, Search engine]  [1, Smartphone]

需要将referrer_type和device_type字段的所有NULL值替换为列表[-1, 'Unknown'],编写的代码如下:

df.loc[df['referrer_type'].isnull(), ['referrer_type']] = df.loc[df['referrer_type'].isnull(), 'referrer_type'].apply(lambda x: [-1, 'Unknown'])

df.loc[df['device_type'].isnull(), ['device_type']] = df.loc[df['device_type'].isnull(), 'device_type'].apply(lambda x: [-1, 'Unknown'])

运行时报错:

NumPy boolean array indexing assignment requires a 0 or 1-dimensional input, input has 2 dimensions

该代码在Google Colab中可正常运行,但在PyCharm中无法执行。

问题原因

核心是Pandas版本差异导致的赋值行为不同:

  • Google Colab默认使用较新的Pandas版本,对二维切片的赋值兼容性更强,能自动处理Series元素为列表的赋值场景;
  • PyCharm环境中的旧版本Pandas,在通过df.loc[..., [列名]]选择二维DataFrame切片时,会严格检查赋值的维度匹配,而apply返回的Series每个元素是二维列表,触发维度不匹配的报错。
解决方法

提供三种可行的修复方案:

方案1:使用fillna直接填充(最简洁)

fillna可以直接指定填充值,无需复杂的索引操作,兼容新旧版本:

df['referrer_type'] = df['referrer_type'].fillna(value=[-1, 'Unknown'])
df['device_type'] = df['device_type'].fillna(value=[-1, 'Unknown'])

方案2:调整loc的列选择方式

去掉列名的方括号,将二维切片转为一维Series切片,赋值时维度匹配:

df.loc[df['referrer_type'].isnull(), 'referrer_type'] = [-1, 'Unknown']
df.loc[df['device_type'].isnull(), 'device_type'] = [-1, 'Unknown']

Pandas会自动将单个列表广播到所有空值对应的位置。

方案3:保留apply但调整切片方式

如果一定要使用apply,只需去掉列名的方括号,确保左右两边都是一维Series:

df.loc[df['referrer_type'].isnull(), 'referrer_type'] = df.loc[df['referrer_type'].isnull(), 'referrer_type'].apply(lambda x: [-1, 'Unknown'])
df.loc[df['device_type'].isnull(), 'device_type'] = df.loc[df['device_type'].isnull(), 'device_type'].apply(lambda x: [-1, 'Unknown'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:25:05