データの準備
視覚化のためにパンダ read_excel()
メソッドを使用して、主要なカナダ移民データセットをダウンロード、インポート、およびクリーンアップしましょう。
df_can = pd.read_excel('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/Canada.xlsx',
sheet_name='Canada by Citizenship',
skiprows=range(20),
skipfooter=2)
print('Data downloaded and read into a dataframe!')
# clean up the dataset to remove unnecessary columns (eg. REG)
df_can.drop(['AREA','REG','DEV','Type','Coverage'], axis = 1, inplace = True)
# let's rename the columns so that they make sense
df_can.rename (columns = {
'OdName':'Country', 'AreaName':'Continent','RegName':'Region'}, inplace = True)
# for sake of consistency, let's also make all column labels of type string
df_can.columns = list(map(str, df_can.columns))
# set the country name as index - useful for quickly looking up countries using .loc method
df_can.set_index('Country', inplace = True)
# add total column
df_can['Total'] = df_can.sum (axis = 1)
# years that we will be using in this lesson - useful for plotting later on
years = list(map(str, range(1980, 2014)))
# print ('data dimensions:', df_can.shape)
ワードクラウド
Word
クラウド(テキストクラウドまたはタグクラウドとも呼ばれます)は単純な方法で機能します。テキストデータのソース(スピーチ、ブログ投稿、データベースなど)に特定の単語が表示されるほど、その単語は大きく太字になります。ワードクラウド。
幸い、Pythonにはword
クラウドを生成するためのPythonパッケージがすでに存在します。と呼ばれるパッケージは、AndreasMuellerword_cloud
によって開発されました。このリンクをたどると、パッケージの詳細を知ることができます。
このパッケージを使用して、特定のテキストドキュメントのワードクラウドを生成する方法を学びましょう。
まず、パッケージをインストールしましょう。
# install wordcloud
# !conda install -c conda-forge wordcloud==1.4.1 --yes
# ! pip install wordcloud
# import package and its set of stopwords
from wordcloud import WordCloud, STOPWORDS
print ('Wordcloud is installed and imported!')
Word
クラウドは通常、テキストデータの高レベルの分析と視覚化を実行するために使用されます。それに応じて、移民データセットから逸脱し、テキストデータの分析を含む例を使用してみましょう。ルイス・キャロルが書いた「不思議の国のアリスの冒険」というタイトルの短い小説を分析してみましょう。先に進んで、小説の.txtファイルをダウンロードしましょう。
# download file and save as alice_novel.txt
!wget --quiet https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/alice_novel.txt
# open the file and read it into a variable alice_novel
alice_novel = open('alice_novel.txt', 'r').read()
print ('File downloaded and saved!')
File downloaded and saved!
次に、からインポートしたストップワードを使用しましょうword_cloud
。関数セットを使用して、冗長なストップワードを削除します。
stopwords = set(STOPWORDS)
ワードクラウドオブジェクトを作成し、ワードクラウドを生成します。簡単にするために、小説の最初の2000語のみを使用してワードクラウドを生成しましょう。
# instantiate a word cloud object
alice_wc = WordCloud(
background_color='white',
max_words=2000,
stopwords=stopwords
)
# generate the word cloud
alice_wc.generate(alice_novel)
驚くばかり!今ではword
雲が作成された、のはそれを視覚化しましょう。
# display the word cloud
plt.imshow(alice_wc, interpolation='bilinear')
plt.axis('off')
plt.show()
面白い!したがって、小説の最初の2000語では、最も一般的な単語はアリス、と言った、リトル、クイーンなどです。クラウドのサイズを変更して、頻度の低い単語が少しよく見えるようにします。
fig = plt.figure()
fig.set_figwidth(14) # set width
fig.set_figheight(18) # set height
# display the cloud
plt.imshow(alice_wc, interpolation='bilinear')
plt.axis('off')
plt.show()
ずっといい!しかし、言ったのは本当に有益な言葉ではありません。それでは、それをストップワードに追加して、クラウドを再生成しましょう。
stopwords.add('said') # add the words said to stopwords
# re-generate the word cloud
alice_wc.generate(alice_novel)
# display the cloud
fig = plt.figure()
fig.set_figwidth(14) # set width
fig.set_figheight(18) # set height
plt.imshow(alice_wc, interpolation='bilinear')
plt.axis('off')
plt.show()
優秀な!これは本当に面白そうです!word_cloud
パッケージで実装できるもう1つの優れた点は、任意の形状のマスクに単語を重ねることです。アリスとうさぎのマスクを使ってみましょう。すでにマスクを作成しているので、ダウンロードしてalice_mask.pngと呼びましょう。
# download image
!wget --quiet https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/labs/Module%204/images/alice_mask.png
# save mask to alice_mask
alice_mask = np.array(Image.open('alice_mask.png'))
print('Image downloaded and saved!')
Image downloaded and saved!
マスクがどのように見えるかを見てみましょう。
fig = plt.figure()
fig.set_figwidth(14) # set width
fig.set_figheight(18) # set height
plt.imshow(alice_mask, cmap=plt.cm.gray, interpolation='bilinear')
plt.axis('off')
plt.show()
シェーピングword
マスクによると、クラウドは使用して簡単ですword_cloud
パッケージを。簡単にするために、小説の最初の2000語を引き続き使用します。
# instantiate a word cloud object
alice_wc = WordCloud(background_color='white', max_words=2000, mask=alice_mask, stopwords=stopwords)
# generate the word cloud
alice_wc.generate(alice_novel)
# display the word cloud
fig = plt.figure()
fig.set_figwidth(14) # set width
fig.set_figheight(18) # set height
plt.imshow(alice_wc, interpolation='bilinear')
plt.axis('off')
plt.show()
本当に印象的です!
残念ながら、私たちの移民データにはテキストデータがありませんが、意志がある場合は方法があります。移民データセットからサンプルテキストデータを生成しましょう。たとえば、90語のテキストデータです。
1980年から2013年までの総移民は何でしたか?
total_immigration = df_can['Total'].sum()
total_immigration
6409153
一言の名前を持つ国を使用して、それらが総移民にどれだけ貢献しているかに基づいて、各国の名前を複製しましょう。
max_words = 90
word_string = ''
for country in df_can.index.values:
# check if country's name is a single-word name
if len(country.split(' ')) == 1:
repeat_num_times = int(df_can.loc[country, 'Total']/float(total_immigration)*max_words)
word_string = word_string + ((country + ' ') * repeat_num_times)
# display the generated text
word_string
'China China China China China China China China China Colombia Egypt France Guyana Haiti India India India India India India India India India Jamaica Lebanon Morocco Pakistan Pakistan Pakistan Philippines Philippines Philippines Philippines Philippines Philippines Philippines Poland Portugal Romania '
ここではストップワードを扱っていないので、ワードクラウドを作成するときにストップワードを渡す必要はありません。
# create the word cloud
wordcloud = WordCloud(background_color='white').generate(word_string)
print('Word cloud created!')
Word cloud created!
# display the cloud
fig = plt.figure()
fig.set_figwidth(14)
fig.set_figheight(18)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
上記のワードクラウドによると、移民した人々の大多数は、ワードクラウドによって表示されている15カ国の1つから来たようです。作成できるクールなビジュアルの1つは、おそらくカナダの地図とマスクを使用し、カナダの地図の上に単語の雲を重ね合わせることです。それは構築するのに面白いビジュアルになるでしょう!