どんどんいきます。”Google Advanced Data Analytics Certificate” シリーズのコース3 “Go beyond the numbers” 「数値を超えて」 です。
いよいよ実際にデータを触ってみる感じの内容ですね。
Module 1: Find and share stories using data
最初に、イントロダクションの動画があり、直後に Deloitte での PACE ワークフローの運用例があります。(というより、データ分析業務の例をPACEに当てはめたケーススタディ)
また、今回のコースでは、EDA: Exploratory Data Analysis にも焦点を当てている。
EDA の6つのステップ:
- Discovering
- Structuring
- Cleaning
- Joining
- Validating
- Presenting
たまに見かける単語があったので、メモで、
You have to understand why it was created and what is and isn’t there and what important caveats are sitting on top of it.
a warning to consider something before taking any more action, or a statement that limits a more general statement:
Cambridge Dictionary – caveat
ここでいう “caveat” は、「注意事項」や「但し書き」という意味です。
データの形式がバラバラであることに起因して、EDA のプロセスは、
- Iterative:反復し
- Non-sequential:順番通りにならない
という性質を持つ
EDA プロセスの重要な原則は以下2つ:
- Human augmentation:AI や機械学習アルゴリズムの間に人間が入り込み、監視することが重要。これによって、バイアスや不正確さを制限できる。
- Bias evaluation:体系的に EDA プロセスを実行することにより、バイアスや偏りに対処することができる。
Module 2: Explore raw data
Module 2 では、Python とデータを用いた実践が入ってきます。
とりあえず、データを操作する前に取り込まなければならないので、Python にデータを取り込む代表的な2種類の方法は以下。
Python の標準ライブラリを利用する方法:
with open('PATH/TO/YOUR/FILE', mode='r') as file:
data = file.read()
pandas に csv ファイルを取り込む方法:
import pandas as pd
df = pd.read_csv('PATH/TO/YOUR/FILE')
pandas では、引数のファイル名の部分に URL を指定して、オンライン上の csv ファイルを取り込むことも可能。
次いで、Google の提供するクラウドデータベースサービス、BigQuery の使い方についても説明があります。これはもう使って慣れるしかないかなと思います。
基本的には、BigQuery にアクセスして -> Public data を検索 -> Query でデータを取得、のような流れになります。
実は BigQuery 上で仮想マシンを走らせることができるみたいですね。これは知らなかったです。この仮想マシンを使って BigQuery のデータセットを操作できる。
EDA ワークフローの、discovering で特に有用な pandas の機能は以下:
Daraframe.head()
Linux のシェルにも同じようなコマンドがありますが、データフレームの先頭から数行を返すメソッドです。引数で、表示する行数を指定することも可能。
df.head(10) # 先頭から10行表示
Daraframe.info()
インデックスの範囲、dtypes、列のヘッダ情報やメモリ消費量などのサマリーを返すメソッド。引数で出力内容のオプションを指定することが可能。
df.info()
Dataframe.describe()
データフレームに関する統計情報を返すメソッド。データカウント、最大値、最小値、平均値、中央値や分散などを返すメソッド。
df.describe()
Dataframe.shape
データフレームの次元を示す属性。メソッドではないことに注意。
A hypothesis is a theory or an explanation based on evidence that is not yet proved true.
仮説とは、根拠に基づいた理論や説明のことであり、まだ真であると証明されていないものである。
初めて聞いた英語の諺があったので、メモで。
In other words leave no stone unturned. It’s an old saying about an ancient Greek legend and it means to search everything you can to think of to find what you’re looking for.
何か探し物なりをしてるなら、「ひっくり返してない石を残さない(全部ひっくり返す)」って意味です。それから、ことわざは ”proverb” 意外にも “old saying” って言えるんですね。こっちの方が口語っぽい。
Datetime manipulation
Python で時間を扱う際によく使われるのが、標準ライブラリに含まれる、datetime モジュールです。
時間や日付を指定する際に、文字列のフォーマット指定子のようなものを扱います。が、「フォーマット指定子」とは呼ばれずに、「フォーマットコード」と呼ばれているみたいです。(C言語の規格に準拠)
The following is a list of all the format codes that the 1989 C standard requires, and these work on all platforms with a standard C implementation.
標準ライブラリのインポートは、
from datetime import datetime
よく使うものは、以下テーブル:
Code | Format | Example |
---|---|---|
%A | Weekday | Sunday |
%d | Day (leading zeros) | 01 to 31 |
%m | Month | 01 to 12 |
%Y | Year | 2024 |
%H | 24 hours | 00 to 23 |
%M | Minute | 00 to 59 |
%S | Second | 00 to 61 |
そして、よく利用される datetime 関連の関数2種類:
Code | Input type | Input example |
---|---|---|
datetime.strptime(“25/11/2022”, “%d/%m/%Y”) | string | “29/06/2024” |
datetime.strftime(dt_object, “%d/%m/%Y”) | datetime | “2024-06-29 00:00:00” |
ちなみに、strptime は “str – p – time” -> String parsed time のことで、strftime は “str – f -time” -> String from time のことです。
あとは、この辺の関数を上のフォーマットコードを組み合わせることで、自由に時間の操作が可能。
また、データ分析でよく用いられるパッケージ NumPy や pandas を使用する際には、標準ライブラリの datetime モジュールではなく、pandas や NumPy で定義されているものを利用した方が良い。
こちらの方が、pandas と NumPy の強みである大量のデータ処理向けに調整してあるもののため。
NumPy の datetime class 例: datetime64, timedelta64 など
Pandas の datetime class 例:Timestamp, Timedelta, Period, DateOffset など
※ その他の多くのモジュールと同様に、pandas の datetime クラスは、NumPy モジュール上に構築されている。
pandas での datetime クラスの使用例:
import pandas as pd
data = ['2023-01-20', '2023-04-27', '2023-06-15']
my_series = pd.Series(data) # 文字列のリストを series オブジェクト化
my_series = pd.to_datetime(my_series) # datetime オブジェクトに変換
print(my_series.dt.year) # 年だけ表示 (シリーズオブジェクトで)
print(my_series.dt.month) # 月だけ表示 (シリーズオブジェクトで)
print(my_series.dt.day) # 日だけ表示 (シリーズオブジェクトで)
“The pandas dt Series accessor (as demonstrated in the last example) is a different thing entirely.” とあるように、”dt” は アクセサーと呼ぶみたいです。
全くデータ分析と関係ないカンガルーの話ですが、These furry creatures are native to Australia and Papa New Guinea. They are known for their strong tails and belly pouch they used to cradle their babies called Joeys. カンガルーの子供って “joey” って言うんですね。熊の子供は、”cub” って言ったり、子猫とか子犬はそれぞれ “kitty” とか “puppy” だったりするので、英語は成体と幼体で分け気味な言語ですね。
Pandas tools for structuring a dataset
pandas パッケージでデータフレームの構築を行う際のリファレンス
Combine data
df.merge():DaraFrame クラスで利用可能なメソッド。呼び出したデータフレームに引数のデータフレームをマージ。
df1.merge(df2, how=‘inner’, on=[‘month’,’year’])
pd.concat():pandas モジュールの関数。シリーズやデータフレームを結合させる。
df3 = pd.concat([df1.drop(['column_1','column_2'], axis=1), df2])
df.join():DataFrame クラスで利用可能なメソッド。SQLの “join” に近い。
df1.set_index('key').join(df2.set_index('key'))
Extract or select data
df[[columns]]:データフレームの一部を切り出す一般的な記法。
df[['animal', 'legs']]
df.select_dtypes():DataFrame クラスで利用可能なメソッド。dtype を指定してデータを切り出す。
df2 = df.select_dtypes(include=['int64'])
Filter data
df[condition]:ブーリアンのマスクを生成する記法。マスクをフィルタリングに利用できる。
df[df['class']=='Aves']
Sort data
df.sort_values():DataFrame クラスのメソッド。データの値をベースに並べ替える。
df.sort_values(by=['legs'], ascending=False)
Slice data
df.iloc[]:インデックス基準でデータフレームのスライスを生成。
df.iloc[5:10, 2:] # selects only rows 5 through 9, at columns 2+
df.loc[]:ラベル名またはブーリアン値をベースにデータフレームのスライスを生成。
df.loc[:, ['color', 'class']]
Histograms
Histograms are commonly used to illustrate the shape of a distribution, including the presence of any outliers, the center of the distribution, and the spread of the data.
データの分布を見るときに利用されるのがヒストグラム。この辺は、最近高校の必修科目に選ばれたとかで記憶に新しいですね。あと、統計学を勉強するときに必須の知識となります。
Histograms are an essential tool for understanding the characteristics of a dataset. They provide a visual representation of the data’s distribution and enable data professionals to identify patterns, trends, or outliers within the data.
データの分布意外にも、パターンや傾向、異常値などを特定する際にも利用される。
ヒストグラムの主な類型:
- Symmetric:テキストでよく見るやつ、左右対称
- Skewed:右または左に歪んだ分布
- Bimodal:山が二つある分布
- Uniform:一様で分布が見えない(データの取り方を再検討)
plt.hist():matplotlib パッケージの関数でヒストグラムの描画ができる。
plt.hist(df['seconds'], bins=range(40, 101, 5))
sns.histplot():seaborn パッケージのヒストグラム描画関数。matplotlib より綺麗
seaborn のオフィシャルには、次のように記述があります。
Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.
seaborn の API 触ると、matplotlib のグラフ描画にも影響が出るのは、seaborn が matplotlib をベースにしてるからなんですね。内部で繋がってるから影響する。
seaborn は、matplotlib のより高機能(充実したインターフェース)のバージョンと思っておきます。
As a data professional I can say that cleaning and organizing your dataset is 90% of the battle and once you structured your tables uncovering insights and trends can be a walk in the park.
「データ分析において、データのクリーニングと編成が作業の90%ぐらい。残りは公園を散歩するのと同じ。」って言うレベルには、前段取りが重要ってことですね。
全てのものごとに言えることですが、いわゆる「段取り八分仕事二分」ってやつです。パーセンテージは違いますけど。
Module 3: Clean your data
データクリーニングで最も基本的なものは、重複の削除。データの特性をよく考えて、削除すべき重複か、残すべき重複かを判断することが肝要。
pandas では、以下の重複に関連したメソッドが利用できる。
df.duplicated():重複行の特定、subset 引数で列の指定、keep 引数で残すデータの選択が可能。戻り値は、要素がブーリアンのシリーズオブジェクトとなる。
df.duplicated(subset=['type'], keep='last')
Don’t be duped — How to do deduplication
to deceive someone, usually by making that person do something that they did not intend to do:
Cambridge Dictionary – dupe
df.drop_duplicates():重複行を削除したデータフレームを返す。subset 引数、keep 引数は df.duplicated() と同。
df = df.drop_duplicates(subset='style')
Remember that data models have lives beyond code blocks and data strings.
データモデルは、そのコードや文字を超えて、存在する。
A documentation string or docstring is a line of text following a method or function that is used to explain to others using your code what this method or function does. A docstring represents good documentation practices in Python.
外れ値は、以下3種に分類できる:
- Global outliers are values that are completely different from the overall data group and have no association with any other outliers. They may be inaccuracies, typographical errors, or just extreme values you typically don’t see in a dataset. -> ぱっと見でわかるやつ。異常な値。
- Contextual outliers are normal data points under certain conditions but become anomalies under most other conditions. -> 許容範囲内のデータポイントだが、データのパターンなどの文脈よっては外れ値になる。
- Collective outliers are a group of abnormal points that follow similar patterns and are isolated from the rest of the population. -> 通常の範囲内のデータだが、一部にデータポイントが異常に密集している、など。
ラベルエンコーディング(カテゴリデータを数値データに変換する)には大きく二つの方法がある:
- Dummy variables are variables with values of 0 or 1, which indicate the presence or absence of something. (also known as one-hot encoding)
- Label encoding is a data transformation technique where each category is assigned a unique number instead of a qualitative value.
上記は以下のように使い分ける
Label encoding is best for large numbers of different categorical variables and for categories that have an inherent order to them. One-hot encoding is best for smaller amounts of categorical variables and for categories that have no order.
基本的には、大量のカテゴリがある場合やカテゴリの順序がある場合に label encoding を利用し、比較的少ないカテゴリの場合やその順序に関係がない場合には、one-hot encoding を使うと良い。
A heatmap is a type of data visualization that depicts the magnitude of an instance or set of values based on two colors.
データクリーニングに有用なメソッドは、以下。
Missing Data
df.info(): A DataFrame method that returns a concise summary of the dataframe.
pd.isna() / pd.isnull(): pd.isna() is a pandas function that returns a same-sized Boolean array indicating whether each value is null (you can also use pd.isnull() as an alias).
pd.notna() / pd.notnull(): pandas function that returns a same-sized Boolean array indicating whether each value is NOT null (you can also use pd.notnull() as an alias).
df.fillna(): A DataFrame method that fills in missing values using specified method
df.replace(): A DataFrame method that replaces specified values with other specified values.
df.dropna(): A DataFrame method that removes rows or columns that contain missing values, depending on the axis you specify.
Outliers
df.describe(): A DataFrame method that returns general statistics about the dataframe which can help determine outliers.
sns.boxplot(): A seaborn function that generates a box plot. Data points beyond 1.5x the interquartile range are considered outliers.
Label encoding
df.astype(): A DataFrame method that allows you to encode its data as a specified dtype.
Series.cat.codes: A Series attribute that returns the numeric category codes of the series.
pd.get_dummies(): A function that converts categorical values into new binary columns—one for each different category
sklearn.preprocessing,LabelEncoder(): A transformer from scikit-learn.preprocessing that encodes specified categories or labels with numeric codes.
Module 4: Data visualizations and presentations
Module 4 は、Data visualization についてです。最初からいきなり Tableau を使う前提で話が進んでいくので、ある程度操作感はわかっておいた方が無難です。一部機能は、アカウント作成すればフリーで利用可能です。Tableau Public
Tableau は、次のようにデータの型を大別している。
Tableau divides all the data fields into two broad data types, dimensions and measures.
- Dimensions are qualitative data values used to categorize and group data to reveal details about it.
- Measures are numeric values that can be aggregated or placed in calculations.
また、同様にデータフィールドリストも色によって分類される。
Green indicates that the data field is continuous, blue indicates that the field is discrete.
データの見せ方には大きく次の戦略がある。
Basic organizing strategies for a presentation:
- Chronological is for data that is best understood in a time series
- Generic-to-specific helps an audience consider an issue before describing how it affects them
- Specific-to-generic is useful to highlight impacts the data can have on a broader scale.
Tableau の文脈において、”story” は、特定の意味を持つ。
A story is a tableau term for a group of dashboards or worksheets assembled into a presentation.
また、”set” も同様に、
A set is a tableau term for a custom field of data created from a larger data set based on custom conditions.
Data visualization に関する有益なリソース:
- Tableau resources:チュートリアルや eラーニング、ドキュメントなど
- Power BI:よりビジネスに特化したデータビジュアライゼーションツール
- Information is Beautiful:データ分析のプロフェッショナルによるコミュニティ、使用データの透明性に重点を置く
- Storytelling with Data:簡潔なデータによるインサイトのコミュニケーションに重きを置いたコミュニティ
- Python Graph Gallery:Python で構成されたヴィジュアルのギャラリー、Python コードを含む
Tableau の文脈における “action” とは、
An action is a Tableau tool to help a user interact with a visualization or dashboard by allowing control of a selection.
Module 4 は、インプットよりもアウトプット中心の教材になります。Tableau を使って自分なりのダッシュボードやストーリーを作成して評価する、といった内容です。
Module 5: Course 3 end-of-course project
最後のモジュールです。これは、 Google Advanced Data Analytics Professional Certificate のそれぞれのコースで共通のテーマで End-of-course project を進めていく内容です。
これまでのコースの通り、基本的にはヒントのあ通りに進めてけば特に難しいこともないかなと。
まとめ
Python を利用して EDA の実践ができるのはいいですね。あと、Tableau で簡単にデータのヴィジュアルを作成できるってのを再確認できるいいコースかと。
続いて、統計学の基礎のコース “The Power of Statistics” 入ります。
それでは!
コメント