我有一个包含电影类型和ID的列表,还有第二个仅包含ID的列表。现在,我尝试使用第一个列表仅获取列表中的流派。这个问题应该很容易,但是我找不到解决方案。
带有电影类型的列表是通过csv文件加载的。看起来像:
Unnamed: 0 id name
0 0 28 Action
1 1 12 Adventure
2 2 16 Animation
3 3 35 Comedy
4 4 80 Crime
5 5 99 Documentary
6 6 18 Drama
7 7 10751 Family
8 8 14 Fantasy
9 9 36 History
10 10 27 Horror
第二个列表如下:
filmgenre = [28, 16, 14, 99]
到目前为止,我的代码:
filmgenreslist = pd.read_csv("genrelist.csv") #load csv
cleanfilmlist = filmgenreslist.loc[:,"name"] #tried to reduce the list to necessary informations
filmgenre = [28, 16, 14, 878]
filmgenrenames = [] #tried to save the genres for later
number = 0 #just to test
test = cleanfilmlist.loc[filmgenreslist["id"] == filmgenre[number]] #try to extract only the genrename
print(test)
#print(test[-1])
#to loop through the data, multiple tries but can't solve
for number in range(5):
try:
#filmgenrenames.append([cleanfilmlist["name"].where(cleanfilmlist["id"] == filmgenre[number])])
filmgenrenames.append([cleanfilmlist.loc(cleanfilmlist["id"] == filmgenre[number])])
#filmgenrenames.append([cleanfilmlist.loc[filmgenreslist["id"] == filmgenre[number]]])
#print(number, filmgenrenames)
except:
filmgenrenames.append(["missing"])
print(filmgenrenames)
我很累得到如下输出:
filmgenresname =["Action","Animation","Fantasy","Documentary","missing"]
答案 0 :(得分:3)
您可以将id作为键的字典,并将name作为值的字典,然后将其与列表映射:
map_id_name = dict(zip(filmgenreslist['id'], filmgenreslist['name']))
list(map(lambda x:map_id_name.get(x, "missing"), filmgenre ))