我有两个列表 my_genre 和 list_of_genres。我想要一个函数来检查 my_list[index] 是否在 list_of_genres 中并将 list_of_genres[index2] 转换为 1 如果是这样的话。
list_of_genres = ['Adventure', 'Animation', 'Children', 'Comedy', 'Fantasy', 'Drama', 'Romance', 'Action', 'Thriller', 'Sci-Fi', 'Crime', 'Horror', 'Mystery', 'IMAX', 'Documentary', 'War', 'Musical', 'Western', 'Film-Noir']
my_genre = ['Action', 'Crime', 'Drama', 'Thriller']
预期结果:
[0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 0 0 0 0]
data type : np.array
最终,我想将执行此操作的函数应用到包含流派的 pandas 列。
请您参考如下方法:
Numpy isin 就是您要找的东西。
results = np.isin(list_of_genres, my_genre).astype(int)
Pandas 也一样。
list_of_genres = ['Adventure', 'Animation', 'Children', 'Comedy', 'Fantasy', 'Drama', 'Romance', 'Action', 'Thriller', 'Sci-Fi', 'Crime', 'Horror', 'Mystery', 'IMAX', 'Documentary', 'War', 'Musical', 'Western', 'Film-Noir']
my_genre = ['Action', 'Crime', 'Drama', 'Thriller']
df = pd.DataFrame({"genres" : list_of_genres})
df["my_genre"] = df["genres"].isin(my_genre).astype(int)
print(df)
