sti320a

勉強したことのまとめ

勉強したことまとめ_2020年04月11日

pandas

  • DataFrame() が引数にとれるデータ(data)の形式を3つあげよ
ndarray, dict, DataFrame。dict は Series, ndarray, list を要素に持てる。
  • pandas は数学演算がうまくいかない場合、結果をどのような値で置き換えるか
NaN値
  • 時系列データの扱い
import numpy as np
import pandas as pd

np.random.seed(100)
# 標準正規分布従うデータをランダムに出力
a = np.random.standard_normal((9, 4))
df = pd.DataFrame(a)


# カラムを設定
df.columns = ['No1', 'No2', 'No3', 'No4']

# 特定のカラムの平均値を計算
df['No2'].mean()

# DatetimeIndex オブジェクトを作成する
dates = pd.date_range('2019-1-1', periods=9, freq='D')

# インデックスを DatetimeIndex に置き換える
df.index = dates

# DataFrame のデータを表示
df.values
  • データの可視化
# DataFrame のメタデータを表示
df.info()

# 要約統計量を表示
df.describe()

df.sum()
df.mean()
df.mean(axis=0)
df.mean(axis=1)

df.cumsum() # 累積和 cumulation sum

# DataFrame は numpy のユニバーサル関数も使用可能
np.mean(df)
np.log(df)
np.sqrt(abs(df))
np.sqrt(abs(df)).sum()

100 * df + 100

# 可視化
from pylab import plt, mpl

# スタイルの設定
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'

# %matplotlib inline

# プロット
df.cumsum().plot()
df.cumsum().plot(kind='bar')

type(df)
  • Seriesオブジェクト
S = pd.Series(np.linspace(0, 15, 7), name="series")
type(S)
s = df['No1']
type(s)
s.mean()
s.plot()
  • グループ化
import pandas as pd
df = pd.DataFrame([[11, 12, 13],[14, 15, 16],[14, 15, 16],[1, 2, 3]],
                  columns=['numbers', 'numbers2', 'numbers3'],
                  index=['A', 'B', 'C', 'D']
                  )

# グループ化
df['Quarter'] = ['A', 'B', 'C', 'A']
groups = df.groupby('Quarter')

groups.size()
groups.mean()
groups.max()

# 集計
groups.aggregate([min, max]).round(2)

# 複数列のグループ化
df['Odd_Even'] = ['Odd', 'Even', 'Odd', 'Even']
groups = df.groupby(['Quarter', 'Odd_Even'])

groups.size()

# 集計
import numpy as np
groups[['numbers', 'numbers3']].aggregate(['sum', np.mean])
groups.aggregate(['sum', np.mean])
  • 論理式による複合選択
data = np.random.standard_normal((10, 2))
df = pd.DataFrame(data, columns=['x', 'y'])
df.info()
df.head()
df.tail()
df['x'] > 0.5
df > 0.5
(df['x'] > 0) & (df['y'] < 0)
(df['x'] > 0) | (df['y'] < 0)
df[df['x'] > 0]
df.query('x > 0')
df.query('x > 0 & y < 0')
df[df > 0]
  • 連結やマージ
df1 = pd.DataFrame(['100', '200', '300', '400'], index=['a', 'b', 'c', 'd'], columns=['A'])
df2 = pd.DataFrame(['200', '300', '400'], index=['f', 'g', 'h'], columns=['B'])
  • 連結
df1.append(df2, sort=False)
pd.concat((df1, df2))
  • 結合
df1.join(df2)
df2.join(df1)
df1.join(df2, how='right')
df1.join(df2, how='inner')
df = pd.DataFrame()
df['A'] = df1['A']
  • マージ
c = pd.Series([250, 150, 50], index=['b', 'd', 'c'])
df1['C'] = c
df2['C'] = c
pd.merge(df1, df2)

テスト

  • テストのピラミッドとは何か
下から順に「Unitテスト」「 統合テスト」「 UIテスト」を積み上げたピラミッド。
Unit テストは、コードレベルでのテストしかできないものの、低コストで高速である。
UIテストは、ユーザーが触れるインターフェースを総合してテストできるため信頼性は高いが、高コストで時間がかかる。
統合テストはその中間。

既存の手法では、UIテストが最も重視され、信頼性と引き換えに莫大な時間とコストを割いていた。
Unit テストは開発者が実装し、高速で検証するサイクルを作れるため、UIテストや統合テストより以前に実施することにより、
開発者にとってもテスターにとってもメリットがあるよ、というお話に用いられる。