質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

723閲覧

Python Youtube APIでタイトルとvideoカウントを抽出する

pon244

総合スコア59

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2020/11/24 11:41

編集2020/11/28 05:57

【環境】
Python3、macbook pro, Jupyter notebook

【コード】

from apiclient.discovery import build YOUTUBE_API_KEY = '自分のAPIキーを入力' youtube = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY) search_response = youtube.search().list( part='snippet', #検索したい文字列を指定 q='荒野行動', #視聴回数が多い順に取得 order='viewCount', type='video', ).execute() def get_video_info(part, q, order, type, num): dic_list = [] search_response = youtube.search().list(part=part,q=q,order=order,type=type) output = youtube.search().list(part=part,q=q,order=order,type=type).execute() #一度に5件しか取得できないため何度も繰り返して実行 for i in range(num): dic_list = dic_list + output['items'] search_response = youtube.search().list_next(search_response, output) output = search_response.execute() df = pd.DataFrame(dic_list) #各動画毎に一意のvideoIdを取得 df1 = pd.DataFrame(list(df['id']))['videoId'] #各動画毎に一意のvideoIdを取得必要な動画情報だけ取得 df2 = pd.DataFrame(list(df['snippet']))[['channelTitle','publishedAt','channelId','title','description']] ddf = pd.concat([df1,df2], axis = 1) return ddf #関数の結果 get_video_info(part='snippet',q='荒野行動',order='viewCount',type='video',num = 20) ###videoカウントを追加する def get_statistics(id): statistics = youtube.videos().list(part = 'statistics', id = id).execute()['items'][0]['statistics'] return statistics df_static = pd.DataFrame(list(df['videoId'].apply(lambda x : get_statistics(x)))) df_output = pd.concat([df,df_static], axis = 1) df_output

【関数の結果】
イメージ説明

【したいこと】
1関数の結果の場所のChannelIDをいれる
2channelIdとVideoViewの新しいDataFrameを作成する
3pd.concatでChannelIDを基準に新しいDFを作成する。
youtube.channels().list(part = 'statistics', id = '').execute()

【エラーメッセージ】
dfが存在しない。
For文なども試しましたが、失敗してしますのでご教授お願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

ひとまず「dfが存在しない。」エラーに関してのみですが、

df_static = pd.DataFrame(list(df['videoId'].apply(lambda x : get_statistics(x))))

の中で、「df」を定義していない状態でdf['video_id']を使おうとしているからです。

直すならば下記のようになります(なお、同時に無駄なquota消費も削減しております)

from apiclient.discovery import build import pandas as pd # <------これがないと動かないはずなので追加 YOUTUBE_API_KEY = '自分のapiキーを入力' youtube = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY) ''' 下8行は不要。無駄にquotaを消費するだけなので削除。 ''' # search_response = youtube.search().list( # part='snippet', # #検索したい文字列を指定 # q='荒野行動', # #視聴回数が多い順に取得 # order='viewCount', # type='video', # ).execute() def get_video_info(part, q, order, type, num): dic_list = [] search_response = youtube.search().list(part=part, q=q, order=order, type=type) ''' youtube.search()を重複して呼び出しているので修正。 ''' # output = youtube.search().list(part=part,q=q,order=order,type=type).execute() output = search_response.execute() #一度に5件しか取得できないため何度も繰り返して実行 for i in range(num): dic_list = dic_list + output['items'] search_response = youtube.search().list_next(search_response, output) output = search_response.execute() df = pd.DataFrame(dic_list) #各動画毎に一意のvideoIdを取得 df1 = pd.DataFrame(list(df['id']))['videoId'] #各動画毎に一意のvideoIdを取得必要な動画情報だけ取得 df2 = pd.DataFrame(list(df['snippet']))[['channelTitle','publishedAt','channelId','title','description']] ddf = pd.concat([df1,df2], axis = 1) return ddf # videoカウントを追加する def get_statistics(id): statistics = youtube.videos().list(part = 'statistics', id = id).execute()['items'][0]['statistics'] return statistics ''' 質問文のコードはただ関数を呼び出すだけになっているが、dfという変数に結果を入れる必要がある。 ''' #関数の結果 df = get_video_info(part='snippet',q='荒野行動',order='viewCount',type='video',num = 20) df_static = pd.DataFrame(list(df['videoId'].apply(lambda x : get_statistics(x)))) df_output = pd.concat([df, df_static], axis = 1) df_output

投稿2020/11/28 06:42

編集2020/11/28 06:49
sfdust

総合スコア1135

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問