データ分析 - nakajima-github/python GitHub Wiki

データ加工

CSV形式のデータの読み込み

CSVファイルを読み込み、先頭5行のみ表示する。先頭5行を表示させることで、どのようなデータ列が存在するのか、それぞれのデータ列の関係性などデータの大枠を掴むことができる。

import pandas as pd
customer_master = pd.read_csv('customer_master.csv')
print(customer_master.head())

データを結合(ユニオン)する

同じ形式のファイルが分割されている場合に結合する。ignore_index=Trueとすることで結合したデータにindexを振り直す。

transaction_1 = pd.read_csv('transaction_1.csv')
transaction_2 = pd.read_csv('transaction_2.csv')
transaction = pd.concat([transaction_1, transaction_2], ignore_index=True)

件数を確認する。

print(len(transaction))
print(len(transaction_1))
print(len(transaction_2))

データを結合(ジョイン)する

データをジョインする場合、主軸になるデータを考えつつ、どの列をキーにジョインするかを考える。つまり、①足りない(付加したい)データ列は何か、②共通するデータ列は何かを考える。

# 主軸にするtransaction_detail、結合するtransactionデータの必要な列のみを引数に渡し、ジョインキーとしてtransaction_idを、ジョインの種類をレフトジョインとして指定する
join_data = pd.merge(transaction_detail, transaction['transaction_id', 'payment_date', 'customer_id'](/nakajima-github/python/wiki/'transaction_id',-'payment_date',-'customer_id'), on='transaction_id', how='left)

必要なデータ列を作る

例えばprice(売上列)を作るために、quantityとitem_priceの掛け算を計算する

join_data['price'] = join_data['quantity'] * join_data['item_price']

データを検算する

print(join_data['price'].sum())
print(transaction['price'].sum())
print(join_data['price'].sum() == transaction['price'].sum())

各種統計量を把握する

データ分析を進めていく上で①欠損している値の状況、②全体の数字感 の2つの数字を知る必要がある。

# isnull()は欠損値をTrue/Falseで返し、Trueの数を列ごとにsum()で合計する
join_data.isnull().sum()
# データ件数(count)、平均値(mean)、標準偏差(std)、最小値(min)、四分位数(25%, 75%)、中央値(50%)、最大値(max)を出力する
join_data.describe()
# 日付列の場合、最小値と最大値を求めるとデータの範囲がわかる
join_data['payment_date'].min()
join_data['payment_date'].max()

月別でデータを集計する

全体の数字感を把握したら、時系列で状況を見てみる。過去数年のデータなどを扱う場合、ビジネスモデルの変化などによりひとまとめに分析すると見誤るケースがある。その場合、データ範囲を絞るケースもある。 groupbyでまとめたい列(payment_month)と、集計方法(sum)を記述する。price列のみを表示するため、price列を指定する。

# データ型を確認する
print(join_data.dtypes)
# 'payment_date'がobject型になっているため、datetime型に変更する
join_data['payment_date'] = pd.to_datetime(join_data['payment_date'])
# 年月列を作成する
join_data['payment_month'] = join_data['payment_date'].dt.strftime('%Y%m')
# 先頭5行を表示する
print(join_data['payment_date', 'payment_month'](/nakajima-github/python/wiki/'payment_date',-'payment_month').head())
# 年月で集計する
print(join_data.groupby('payment_month').sum()['price'])

月別、商品別でデータを集計する

# まとめたい列が複数ある場合、groupbyでリスト型を指定する。
print(join_data.groupby(['payment_month', 'item_name']).sum()['price', 'quantity'](/nakajima-github/python/wiki/'price',-'quantity'))
# pivot_tableを使用して集計する
# 行に商品名、列に年月、集計したい数値列(price, quantity)、集計方法にsumを指定する
print(pd.pivot_table(join_data, index='item_name', columns='payment_month', values=['price', 'quantity'], aggfunc='sum'))

商品別の売上推移を可視化する

graph_data = pd.pivot_table(join_data, index='payment_month', columns='item_name', values='price', aggfunc='sum')

import matplotlib.pyplot as plt
plt.plot(list(graph_data.index), graph_data['PC-A'], label='PC-A')
plt.plot(list(graph_data.index), graph_data['PC-B'], label='PC-B')
plt.plot(list(graph_data.index), graph_data['PC-C'], label='PC-C')
plt.plot(list(graph_data.index), graph_data['PC-D'], label='PC-D')
plt.plot(list(graph_data.index), graph_data['PC-E'], label='PC-E')
# 凡例を表示する
plt.legend()
# グラフを表示する
plt.show()