gpt4 book ai didi

python - Numpy选择返回 bool 错误消息

转载 作者:行者123 更新时间:2023-12-03 20:27:42 27 4
gpt4 key购买 nike

我想在路径中找到匹配的字符串,并使用 np.select 创建一个新列,其标签取决于我找到的匹配项。

这是我写的

import numpy as np
conditions = [a["properties_path"].str.contains('blog'),
a["properties_path"].str.contains('credit-card-readers/|machines|poss|team|transaction_fees'),
a["properties_path"].str.contains('signup|sign-up|create-account|continue|checkout'),
a["properties_path"].str.contains('complete'),
a["properties_path"] == '/za/|/',
a["properties_path"].str.contains('promo')]
choices = [ "blog","info_pages","signup","completed","home_page","promo"]
a["page_type"] = np.select(conditions, choices, default=np.nan)

但是,当我运行此代码时,我收到此错误消息:

ValueError: invalid entry 0 in condlist: should be boolean ndarray



这是我的数据示例
3124465                                       /blog/ts-st...
3124466 /card-machines
3124467 /card-machines
3124468 /card-machines
3124469 /promo/our-gift-to-you
3124470 /create-account/v1
3124471 /za/signup/
3124472 /create-account/v1
3124473 /sign-up
3124474 /za/
3124475 /sign-up/cart
3124476 /checkout/
3124477 /complete
3124478 /card-machines
3124479 /continue
3124480 /blog/article/get-car...
3124481 /blog/article/get-car...
3124482 /za/signup/
3124483 /credit-card-readers
3124484 /signup
3124485 /credit-card-readers
3124486 /create-account/v1
3124487 /credit-card-readers
3124488 /point-of-sale-app
3124489 /create-account/v1
3124490 /point-of-sale-app
3124491 /credit-card-readers

最佳答案

.str方法对对象列进行操作。此类列中可能包含非字符串值,因此 pandas返回 NaN对于这些行而不是 False . np然后提示,因为这不是 bool 值。

幸运的是,有一个参数可以处理这个问题:na=False

a["properties_path"].str.contains('blog', na=False)

或者,您可以将条件更改为:
a["properties_path"].str.contains('blog') == True
#or
a["properties_path"].str.contains('blog').fillna(False)

样本
import pandas as pd
import numpy as np

df = pd.DataFrame({'a': [1, 'foo', 'bar']})
conds = df.a.str.contains('f')
#0 NaN
#1 True
#2 False
#Name: a, dtype: object

np.select([conds], ['XX'])
#ValueError: invalid entry 0 in condlist: should be boolean ndarray

conds = df.a.str.contains('f', na=False)
#0 False
#1 True
#2 False
#Name: a, dtype: bool

np.select([conds], ['XX'])
#array(['0', 'XX', '0'], dtype='<U11')

关于python - Numpy选择返回 bool 错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57316346/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com