Zaf*_*rmk 1 python numpy list pandas data-science
我有两个列表my_genre和list_of_genres。我想要一个函数来检查是否my_list[index]在list_of_genres并转换list_of_genres[index2]成1if的情况。
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']
Run Code Online (Sandbox Code Playgroud)
预期结果:
[0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 0 0 0 0]
data type : np.array
Run Code Online (Sandbox Code Playgroud)
最终,我想将执行此操作的功能应用于包含流派的pandas列。
Numpy isin是您想要的。
results = np.isin(list_of_genres, my_genre).astype(int)
Run Code Online (Sandbox Code Playgroud)
熊猫也一样。
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |