首页 > 解决方案 > 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

标签: pythonpandasdataframe

解决方案


问题是它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]

推荐阅读