.isin()和字符串(Python/Pandas)的奇怪问题

2024-04-24 13:50:12 发布

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

我对Pandas.isin()方法有一个奇怪的问题。我正在做一个项目,我需要通过长度、常见单词/密码列表等来识别错误密码(别担心,这是来自公共资源的)。其中一个方法是查看是否有人使用他们名字的一部分作为密码。我正在使用.isin()来确定是否是这样,但它给了我奇怪的结果。显示:

# Extracting first and last names into their own columns
users['first_name'] = users.user_name.str.extract('(^.+)(\.)', expand = False)[0]
users['last_name'] = users.user_name.str.extract('\.(.+)', expand = False)

# Flagging the users with passwords that matches their names
users['uses_name'] = (users['password'].isin(users.first_name)) | (users['password'].isin(users.last_name))

# Looking at the new data
print(users[users['uses_name']][['password','user_name','first_name','last_name','uses_name']].head())

其输出为:

^{pr2}$

基本上是好的;米尔福德哈伯德是使用'hubbard'作为密码,等等,但是我们有几个类似于第一个例子的例子。尽管诺琳·黑尔的密码是“墨菲”,但她的名字只有一个字母。在

我一辈子都搞不清是什么原因造成的。有人知道为什么会发生这种情况,以及如何解决它吗?在


Tags: 方法name密码namesextractpassword名字users
0条回答
网友
1楼 · 发布于 2024-04-24 13:50:12

关于发生此错误的原因:

如果users['password'].isin(users.first_name),则询问users['password']的每一行是否包含在列first\u name中的任何元素中 因此,我假设murphy元素就在这个列的某个地方

网友
2楼 · 发布于 2024-04-24 13:50:12

因为您需要比较同一行中的相邻列,所以矢量化在这里不是一个很好的选择。因此,您可以使用(可能)最快的替代方法:列表理解:

df['uses_name'] = [
       pwd in name for name, pwd in zip(df.user_name, df.password)
]

或者,如果不喜欢循环,可以使用np.vectorize隐藏它们:

^{pr2}$

df
   password            user_name  uses_name
7    murphy          noreen.hale      False
11  hubbard      milford.hubbard       True
22  woodard        jenny.woodard       True
30     reid         rosanna.reid       True
58   golden  rosalinda.rodriquez      False

考虑到您从user_name提取first_name和{},我认为您不需要它。在

相关问题 更多 >