Word Clouds | Python Word Cloudチュートリアル(DVwPノート)

よりおよそパンダエントリ内のデータフレームの一般的な機能

ワードクラウドチュートリアル

データの準備

視覚化のためにパンダ 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つは、おそらくカナダの地図とマスクを使用し、カナダの地図の上に単語の雲を重ね合わせることです。それは構築するのに面白いビジュアルになるでしょう!

おすすめ

転載: blog.csdn.net/weixin_43360896/article/details/111932683