python - Pandas 是 Column 中的字符串
问题描述
尝试拉出“流派”列并检查输入字符串。如果输入在该列中,则返回具有该关键字的所有行。对此有点新意。什么都试过了。包括.isin
import requests
import pandas as pd
movie_list = pd.read_csv ('https://datasets.imdbws.com/title.basics.tsv.gz', low_memory= False, delimiter= "\t", names=["Const", "Type", "Title", "Alt", "Adult", "Start", "End", "Run", "Genre"], usecols= ["Title", "Adult", "Start", "Run", "Genre"])
print("Hello\n\n")
def Choose():
print("Choose an Option\n\n1: Search by Title\n\n2: Choose Categories\n\n3: Random Selection\n")
choice = input()
if choice == "1":
title = input("Enter your title.\n\n")
print (movie_list.loc[movie_list["Title"] == title])
if choice == "2":
genre_exists = 0
while genre_exists < 1:
genre = input("\nChoose a Genre:\n\n")
if genre in movie_list["Genre"]:
print (movie_list.loc[movie_list["Genre"] == genre])
genre_exists += 1
break
else:
print("Try Again")
continue
解决方案
问题是它if genre in movie_list["Genre"]:
会返回False
,因为 movie_list["Genre"] 是类型pd.Series
并且没有与数组相同的行为。例如,"a" in pd.Series(["a"])
也将返回False
。
相反,您可以尝试if genre in movie_list["Genre"].unique():
哪个会按预期工作,因为movie_list["Genre"].unique()
它是一个 numpy 数组。
另一种选择是因为只要任何行包含流派if movie_list.Genre.str.contains(genre).any()
,它就会返回。True
样本输出:
>>> Choose()
Choose an Option
1: Search by Title
2: Choose Categories
3: Random Selection
2
Choose a Genre:
Animation,Short
Title Adult Start Run Genre
2 Le clown et ses chiens 0 1892 5 Animation,Short
4 Un bon bock 0 1892 12 Animation,Short
15 Autour d'une cabine 0 1894 2 Animation,Short
231 Choque de dos transatlánticos 0 1899 2 Animation,Short
249 Matches: An Appeal 0 1899 1 Animation,Short
... ... ... ... .. ...
8317111 EverQuest II Lore in a Minute! 0 2014 \N Animation,Short
8317161 EverQuest Next Lore in a Minute! 0 2014 \N Animation,Short
8317162 DC Universe Online Lore in a Minute! 0 2014 \N Animation,Short
8317167 Dark Souls II Lore in a Minute! 0 2014 \N Animation,Short
8317181 Diablo 3 Lore in a Minute! 0 2014 \N Animation,Short
[33734 rows x 5 columns]
推荐阅读
- python - Python使用子进程windows 10在python中运行可执行文件
- c - 行和列之间的终端间距
- angular - 在 iOS 设备上,为什么 Ionic 4 Infinite Scroll 会在 ionInfinite 事件触发时跳转到页面顶部?
- sql - SQL-遍历 WHERE 子句值列表
- ios - Objective-C/Swift 中除了 os_unfair_lock 之外还有其他原生的 C 级锁吗?
- asp.net - 从 Global.asax 执行 Javascript 函数
- python - 这个程序有什么问题?为什么我在以下 python 代码中出现运行时错误?
- php - Magento 2.3 库存管理,库存价值来自外部系统
- macos - 用于挂载网络卷的本机 API
- glsl - 将 ShaderToy Chromakey 示例移植到 P5.js