【问题标题】:How to display the value that in the same row which matched with the input?如何显示与输入匹配的同一行中的值?
【发布时间】:2020-04-04 10:20:31
【问题描述】:

数据有 2 列,分别为 titlegenre。所以我试图给与用户输入流派匹配的行的title 值。

这是我的尝试:

#CSV READ & GENRE-TITLE
data = pd.read_csv("data.csv")
df_title = data["title"]
df_genre = data["genre"]

#TOKENIZE
tokenized_genre = [word_tokenize(i) for i in df_genre]
tokenized_title = [word_tokenize(i) for i in df_title]

#INPUT-DATA MATCH
search = {e.lower() for l in tokenized_genre  for e in l}
choice = input('Please enter a word = ')

while choice != "exit":
    if choice.lower() in search:
        print(data.loc[data.genre == {choice}, 'title'])
    else:
        print("The movie of the genre doesn't exist")
    choice = input("Please enter a word = ")

但结果是:Series([], Name: title, dtype: object)

我该如何解决?

编辑: 标题的数据样本

0                              The Story of the Kelly Gang
1                                           Den sorte drøm
2                                                Cleopatra
3                                                L'Inferno
4        From the Manger to the Cross; or, Jesus of 
...

对于流派:

0          Biography, Crime, Drama
1                            Drama
2                   Drama, History
3        Adventure, Drama, Fantasy
4                 Biography, Drama
...

【问题讨论】:

  • 您能否提供儿子的样本数据,以便我们为您提供准确的帮助?我想你可以在这里只保留一个DataFrame
  • @s.k 感谢提醒,编辑帖子并添加示例。

标签: python pandas nlp nltk


【解决方案1】:

仅基于Pandas 的一个提案

我会建议这样的事情(请根据您的意愿调整您的情况,这只是一些一般性的指导方针和提示,您可以从哪里开始):

import pandas as pd

# Warning: there are coma and semi-column in some of the films titles,
# so I had to use an other separator when exporting data to CSV, 
# here I decided to chose the vertical bar '|' as you can see)

#CSV READ & GENRE-TITLE
data = pd.read_csv("data.csv", sep="|")

choice = input('Please enter a word = ')

while choice != "exit":
    choice = choice.lower()
    for index, row in data.iterrows():
        if choice in row['genre'].lower():
            print(row['title'])
        else:
            print(("The movie of the genre {} doesn't exist").format(choice))
    choice = input("Please enter a word = ")


编辑

生成随机数:

from random import randint
i = randint(0, len(data))

然后,使用 i 作为索引在您的 DataFrame 中进行搜索。
我让你玩弄这个。



有用的链接

Does Python have a string 'contains' substring method?
How to iterate over rows in a DataFrame in Pandas?

【讨论】:

  • 谢谢,它有帮助,只是稍作修改,现在可以工作,但还有一点细节,我需要它从row[title] 中随机提供一个,现在它在文件中列出了所有这些。你有什么建议吗?
  • 您可以将它们存储在列表或任何其他您想要的结构中,而不是打印结果,然后在 0 和该结构的长度之间选择一个随机数 i 以打印 i -th 元素。文档:docs.python.org/3/library/random.html
  • 再次感谢,无法处理那些随机数的东西,但我用 result = [row['title']]print(random.sample(result, 1)[0]) 处理了
  • 我已经添加了随机数生成。我让你自己试试,从现在开始没那么难了。
  • 啊我现在明白你的意思了,但它应该只从列表中随机建议一个“标题”/项目,我歪曲了。所以选择一个随机数来显示是没用的吗?还是我又误会了? :D
猜你喜欢
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
  • 2019-09-12
  • 1970-01-01
  • 2016-04-16
相关资源
最近更新 更多