【问题标题】:Python dataframe issuePython数据框问题
【发布时间】:2014-10-13 00:18:04
【问题描述】:

我有以下数据框。它来自imdb。我需要做的是提取得分低于 5 且获得超过 100000 票的电影。我的问题是我不明白关于 voting 的最后几行代码的真正作用。

# two lists, one for movie data, the other of vote data
movie_data=[]
vote_data=[]
# this will do some reformating to get the right unicode escape for 
hexentityMassage = [(re.compile('&#x([^;]+);'), lambda m: '&#%d;' % int(m.group(1), 16))] # converts XML/HTML entities into unicode string in Python
for i in range(20):
    next_url = 'http://www.imdb.com/search/title?sort=num_votes,desc&start=%d&title_type=feature&year=1950,2012'%(i*50+1)
    r = requests.get(next_url)
    bs = BeautifulSoup(r.text,convertEntities=BeautifulSoup.HTML_ENTITIES,markupMassage=hexentityMassage)
    # movie info is found in the table cell called 'title'
    for movie in bs.findAll('td', 'title'):
        title = movie.find('a').contents[0].replace('&','&') #get '&' as in 'Batman & Robin'
        genres = movie.find('span', 'genre').findAll('a')
        year = int(movie.find('span', 'year_type').contents[0].strip('()'))
        genres = [g.contents[0] for g in genres]
        runtime = movie.find('span', 'runtime').contents[0]
        rating = float(movie.find('span', 'value').contents[0])
        movie_data.append([title, genres, runtime, rating, year])
    # rating info is found in a separate cell called 'sort_col'
    for voting in bs.findAll('td', 'sort_col'):
        vote_data.append(int(voting.contents[0].replace(',','')))

【问题讨论】:

  • 你已经标记了这个pandas,但看起来你没有在这段代码sn-p中使用它,这主要是BeautifulSoup
  • 为什么要包含第一个循环,因为它与您的问题无关?

标签: python pandas imdb


【解决方案1】:

你的问题是这个sn-p,

for voting in bs.findAll('td', 'sort_col'):
    vote_data.append(int(voting.contents[0].replace(',','')))

在这里,您将遍历所有具有sort_col 属性的td 标记。在这种情况下,他们有class="sort_col"

在第二行,

  • 您正在将',' 替换为voting.contents 返回的列表的第一个元素的''(空字符串)。
  • 将其投射到int
  • 然后将其附加到vote_data

如果我分手了,就会变成这样,

for voting in bs.findAll('td', 'sort_col'):
    # voting.contents returns a list like this [u'377,936']
    str_vote = voting.contents[0]
    # str_vote will be '377,936' 
    int_vote = int(str_vote.replace(',', ''))
    # int_vote will be 377936
    vote_data.append(int_vote) 

打印循环中的值以获得更多理解。如果您正确地标记了您的问题,您可能会更快地得到一个好的答案。

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 2021-12-29
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    相关资源
    最近更新 更多