基于多个条件追加列

2024-10-04 03:26:14 发布

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

我想创建一个新列,如果多个列有nan值,则添加数字1。但是,当我运行我编写的代码时,我不断遇到一条错误消息

df_test2['notsure']=np.where((df_test2[df_test2[['android','blackberry','chrome_os','linux',
                  'macintosh','tizen','windows_phone','windows',
                  'ipad','iphone','device_other']].isna().any(1)]),1,0)

错误消息:

ValueError: Length of values does not match length of index


Tags: of代码消息dfwindows错误np数字
1条回答
网友
1楼 · 发布于 2024-10-04 03:26:14

以下是必要的按嵌套列表筛选:

cols = ['android','blackberry','chrome_os','linux',
        'macintosh','tizen','windows_phone','windows',
        'ipad','iphone','device_other']

df_test2['notsure'] = np.where(df_test2[cols].isna().any(1),1,0)

另一种方法是将布尔掩码转换为True/False1,0映射的整数:

df_test2['notsure'] = df_test2[cols].isna().any(1).astype(int)

相关问题 更多 >