備忘録として
DataFrameの作成
import numpy as np
import pandas as pd
A = np.random.randint(10, size=(3, 4))
df = pd.DataFrame(A, columns=list('QRST')
df
# Q R S T
# 0 1 5 4 1
# 1 9 5 9 1
# 2 2 4 1 5
DataFrameの各行から0行目を引く
df - df.iloc[0]
# Q R S T
# 0 0 0 0 0
# 1 8 0 5 0
# 2 1 -1 -3 4
列単位で引き算する場合は、axisキーワードで指定する
axisキーワードは0が縦(row)方向、1が横(column)方向。それぞれaxis='rows', axis='columns'でも指定できる
DataFrameの各列から0列目を引く場合
df.subtract(df.iloc[:, 0], axis=0)
# Q R S T
# 0 0 4 3 0
# 1 0 -4 0 -8
# 2 0 2 -1 3
Seriesオブジェクトで引く場合も同様
DataFrameオブジェクトとSeriesオブジェクトのインデックスが一致している必要がある
s = pd.Series(np.full(3, 10))
s
# 0 10
# 1 10
# 2 10
# dtype: int64
df.subtract(s, axis=0)
# Q R S T
# 0 -9 -5 -6 -9
# 1 -1 -5 -1 -9
# 2 -8 -6 -9 -5