gpt4 book ai didi

python - 类型错误 : unsupported operand type(s) for |: 'str' and 'bool'

转载 作者:行者123 更新时间:2023-12-01 22:06:19 28 4
gpt4 key购买 nike

我有具有不同列的数据框用户。我的目标是添加 [uses_name] 列,当密码与每个用户的名字或姓氏相同时,该列应为 True

例如,十二行中的 [user_name] 包含 milford.hubbard。那么 [uses_name] 将为 True,因为 [password] 和 [last_name] 相同。

为此,我使用正则表达式创建了两列 [first_name] 和 [last_name]。创建 [uses_name] 时,我在使用 | 运算符时遇到问题。我在 pandas 文档中阅读了有关 boolean 索引的更多内容,但没有找到答案。

我的代码:

import pandas as pd

users = pd.read_csv('datasets/users.csv')

# Extracting first and last names into their own columns

users['first_name'] = users['user_name'].str.extract(r'(^\w+)', expand=False)

users['last_name'] = users['user_name'].str.extract(r'(\w+$)', expand=False)

# Flagging the users with passwords that matches their names

users['uses_name'] = users['password'].isin(users['first_name'] | users['last_name'])

# Counting and printing the number of users using names as passwords

print(users['uses_name'].count())

# Taking a look at the 12 first rows

print(users.head(12))

当我尝试编译它时,出现错误:

TypeError: unsupported operand type(s) for |: 'str' and 'bool'

users 数据框中的前 12 行,其中创建了 first_namelast_name 列:

id          user_name            password   first_name  last_name
0 1 vance.jennings joobheco vance jennings
1 2 consuelo.eaton 0869347314 consuelo eaton
2 3 mitchel.perkins fabypotter mitchel perkins
3 4 odessa.vaughan aharney88 odessa vaughan
2 3 mitchel.perkins fabypotter mitchel perkins
3 4 odessa.vaughan aharney88 odessa vaughan
4 5 araceli.wilder acecdn3000 araceli wilder
5 6 shawn.harrington 5278049 shawn harrington
6 7 evelyn.gay master evelyn gay
7 8 noreen.hale murphy noreen hale
8 9 gladys.ward lwsves2 gladys ward
9 10 brant.zimmerman 1190KAREN5572497 brant zimmerman
10 11 leanna.abbott aivlys24 leanna abbott
11 12 milford.hubbard hubbard milford hubbard

最佳答案

这有效:

users['uses_name']= (users['password']==users['first_name'] )| (users['password']==users['last_name'])

关于python - 类型错误 : unsupported operand type(s) for |: 'str' and 'bool' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49364654/

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