1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonデータ分析と可視化の基本

Last updated at Posted at 2024-08-02

前書き

Pythonはデータ分析や可視化の分野で非常に強力なツールを提供しています。本記事では、具体的なデータ分析と可視化の例を通じて、Pythonを使った実践的な手法を紹介します。
実行結果を加えてQiita用の記事としてまとめます。以下に実行結果の画像を含めた完全な記事を示します。

1. データの作成と基本統計量の計算

Pythonでは、データの作成とその基本統計量の計算が簡単に行えます。以下はその具体例です。

まず、ランダムデータを含むDataFrameを作成します。このDataFrameには3つの列(A、B、C)があり、それぞれランダムな数値が格納されています。

import pandas as pd
import numpy as np

# サンプルデータの作成
data = pd.DataFrame({
    'A': np.random.randn(100),
    'B': np.random.rand(100),
    'C': np.random.rand(100)
})

次に、各列の基本統計量(平均、中央値、分散、標準偏差)を計算して表示します。これにより、データの中心傾向やばらつきを把握できます。

# 基本統計量の計算と表示
print("Mean:\n", data.mean())
print("Median:\n", data.median())
print("Variance:\n", data.var())
print("Standard Deviation:\n", data.std())

実行結果

Mean:
 A    -0.048305
B     0.510058
C     0.491047
dtype: float64
Median:
 A    -0.063992
B     0.499608
C     0.508349
dtype: float64
Variance:
 A    0.982269
B    0.091010
C    0.085688
dtype: float64
Standard Deviation:
 A    0.991104
B    0.301681
C    0.292748
dtype: float64

2. データの可視化

データの可視化は、データの特性を視覚的に理解するために重要です。以下は、MatplotlibとSeabornを使用したデータの可視化の例です。

ヒストグラムの作成

ヒストグラムを使用すると、データの分布を視覚的に確認できます。

import matplotlib.pyplot as plt

# ヒストグラムの作成
plt.figure(figsize=(10, 6))
plt.hist(data['A'], bins=30, alpha=0.5, label='A')
plt.hist(data['B'], bins=30, alpha=0.5, label='B')
plt.hist(data['C'], bins=30, alpha=0.5, label='C')
plt.legend(loc='upper right')
plt.title('Histogram')
plt.show()

実行結果

スクリーンショット 2024-08-02 22.27.59.png

散布図の作成

散布図は、2つの変数間の関係を視覚的に確認するために使用されます。

# 散布図の作成
plt.figure(figsize=(10, 6))
plt.scatter(data['A'], data['B'], alpha=0.5)
plt.title('Scatter Plot between A and B')
plt.xlabel('A')
plt.ylabel('B')
plt.show()

実行結果

スクリーンショット 2024-08-02 22.29.08.png

箱ひげ図の作成

箱ひげ図は、データの分布や異常値を視覚的に確認するためのツールです。

import seaborn as sns

# 箱ひげ図の作成
plt.figure(figsize=(10, 6))
sns.boxplot(data=data)
plt.title('Box Plot')
plt.show()

実行結果

スクリーンショット 2024-08-02 22.30.09.png

3. データのクリーニング

データ分析において、データのクリーニングは欠かせないステップです。以下は、欠損値の処理や異常値の検出と処理の例です。

欠損値の処理

データに欠損値が含まれている場合、適切な方法で補完する必要があります。

# 欠損値の処理
data_with_nan = data.copy()
data_with_nan.iloc[0, 0] = np.nan  # 一つの欠損値を追加
print("Before filling NaN:\n", data_with_nan.head())

# 欠損値の補完
data_filled = data_with_nan.fillna(data_with_nan.mean())
print("After filling NaN:\n", data_filled.head())

実行結果

Before filling NaN:
          A         B         C
0       NaN  0.583585  0.850682
1  0.283692  0.563157  0.763359
2  0.872019  0.295104  0.293991
3 -0.064257  0.682568  0.309063
4 -1.061786  0.336252  0.266989

After filling NaN:
          A         B         C
0 -0.048305  0.583585  0.850682
1  0.283692  0.563157  0.763359
2  0.872019  0.295104  0.293991
3 -0.064257  0.682568  0.309063
4 -1.061786  0.336252  0.266989

異常値の検出と処理

異常値はデータ分析の結果を歪める可能性があるため、適切に処理する必要があります。

# 異常値の検出と処理
data_with_outliers = data.copy()
data_with_outliers.iloc[0, 0] = 999  # 一つの異常値を追加
print("Before removing outliers:\n", data_with_outliers.head())

# 異常値の処理
data_without_outliers = data_with_outliers[data_with_outliers['A'] < 3]
print("After removing outliers:\n", data_without_outliers.head())

実行結果

Before removing outliers:
            A         B         C
0  999.000000  0.583585  0.850682
1    0.283692  0.563157  0.763359
2    0.872019  0.295104  0.293991
3   -0.064257  0.682568  0.309063
4   -1.061786  0.336252  0.266989

After removing outliers:
           A         B         C
1   0.283692  0.563157  0.763359
2   0.872019  0.295104  0.293991
3  -0.064257  0.682568  0.309063
4  -1.061786  0.336252  0.266989
5   0.281592  0.212844  0.489092

4. Seabornによるペアプロットの作成

Seabornは、統計データの可視化を簡単に行うための高レベルなインターフェースを提供します。ペアプロットは、複数の変数間の関係を視覚的に確認するのに役立ちます。

# ペアプロットの作成
sns.pairplot(data)
plt.show()

実行結果

スクリーンショット 2024-08-02 22.31.05.png

5. Bokehによるインタラクティブなプロットの作成

Bokehは、インタラクティブなWebベースの可視化を作成するためのライブラリです。以下は、Bokehを使用したインタラクティブな散布図の作成例です。

from bokeh.plotting import figure, show, output_file
import webbrowser

# HTMLファイルに出力
output_file("scatter_plot.html")

# Bokehプロットの作成
p = figure(title="Scatter Plot of A vs B", x_axis_label='A', y_axis_label='B')

# 散布図の追加
p.scatter(data['A'], data['B'], legend_label='A vs B', fill_alpha=0.6, size=10)

# プロットの表示
show(p)

# ブラウザで自動的に開く
webbrowser.open("scatter_plot.html")

実行結果

スクリーンショット 2024-08-02 22.32.02.png

まとめ

この記事では、データの基本統計量の計算と可視化、データのクリーニング、インタラクティブなプロットの作成など、Pythonを使ったデータ分析と可視化の基本的な手法を紹介しました。各モジュールの使い方を理解し、実際に手を動かして試してみてください。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?