Pandas 检查字符串中的每个单词是否存在于列表中
Pandas check whether every word in a string exists in a list
我有一列艺术家姓名,我想弄清楚艺术家是否使用了他们的真名。所以我整理了一份流行的名字或姓氏列表,并将其放入一个集合中。我现在正在尝试遍历每个艺术家姓名中的所有单词,并检查它们是否在集合中。我已将所有字符串拆分为列表 (df["artist_name"].str.split()) 但不知道如何遍历列表中的所有单词。
我们可以遍历艺术家姓名并检查它是否存在于真实姓名列表中。
import pandas as pd
Panda = pd.read_csv("Artist_Details")
RealNames = [# This List will contain the real names of the artists.]
ArtistList = list(Panda['Artist'])
for Artist in ArtistList:
if Artist not in RealNames:
print(Artist)
对于存储在变量name
中的单个名称和存储在变量nameList
中的列表,您可以通过运行 name in nameList
检查名称是否在列表中].
如果您有一个 fullName
变量,可能包含由 space 分隔的名字和姓氏,您可以执行以下操作:
any([name in nameList for name in fullName.split()])
如果艺术家的名字或姓氏在您要比较的列表中,这将 return True
。如果您想创建更严格的比较并要求名字和姓氏都在列表中,您可以将 any
替换为 all
。
下面的代码使用名为 artistNames
的 pandas 系列和名为 nameList
的列表进行比较。
nameList = ['Fred','Steve','Susan','Jane','Robertson','Jones']
artistNames = pd.Series(['Steve Musicianson','NotARealName McRobotFace','Susan Artistsdottir','Fred Jones'])
anyRealName = artistNames.apply(lambda x: any(map(lambda y: y in nameList, x.split())))
allRealName = artistNames.apply(lambda x: all(map(lambda y: y in nameList, x.split())))
在此代码中,anyRealName
将 return
0 True
1 False
2 True
3 True
而 allRealName
将 return
0 False
1 False
2 False
3 True
我有一列艺术家姓名,我想弄清楚艺术家是否使用了他们的真名。所以我整理了一份流行的名字或姓氏列表,并将其放入一个集合中。我现在正在尝试遍历每个艺术家姓名中的所有单词,并检查它们是否在集合中。我已将所有字符串拆分为列表 (df["artist_name"].str.split()) 但不知道如何遍历列表中的所有单词。
我们可以遍历艺术家姓名并检查它是否存在于真实姓名列表中。
import pandas as pd
Panda = pd.read_csv("Artist_Details")
RealNames = [# This List will contain the real names of the artists.]
ArtistList = list(Panda['Artist'])
for Artist in ArtistList:
if Artist not in RealNames:
print(Artist)
对于存储在变量name
中的单个名称和存储在变量nameList
中的列表,您可以通过运行 name in nameList
检查名称是否在列表中].
如果您有一个 fullName
变量,可能包含由 space 分隔的名字和姓氏,您可以执行以下操作:
any([name in nameList for name in fullName.split()])
如果艺术家的名字或姓氏在您要比较的列表中,这将 return True
。如果您想创建更严格的比较并要求名字和姓氏都在列表中,您可以将 any
替换为 all
。
下面的代码使用名为 artistNames
的 pandas 系列和名为 nameList
的列表进行比较。
nameList = ['Fred','Steve','Susan','Jane','Robertson','Jones']
artistNames = pd.Series(['Steve Musicianson','NotARealName McRobotFace','Susan Artistsdottir','Fred Jones'])
anyRealName = artistNames.apply(lambda x: any(map(lambda y: y in nameList, x.split())))
allRealName = artistNames.apply(lambda x: all(map(lambda y: y in nameList, x.split())))
在此代码中,anyRealName
将 return
0 True
1 False
2 True
3 True
而 allRealName
将 return
0 False
1 False
2 False
3 True