1
私はDataFrame a
とシリーズb
を持っています。私は、それぞれの列の条件付き相関がb
の条件付きでb
になるようにしたいと考えています。具体的には、pd.cut
を使用してb
を5つのグループに分類しています。しかし、標準分位数の代わりに、標準偏差がb
を上回るか下回って使用しています。Groupby + DataFrameとシリーズ間の相関
np.random.seed(123)
a = (pd.DataFrame(np.random.randn(1000,3))
.add_prefix('col'))
b = pd.Series(np.random.randn(1000))
mu, sigma = b.mean(), b.std()
breakpoints = mu + np.array([-2., -1., 1., 2.]) * sigma
breakpoints = np.append(np.insert(breakpoints, 0, -np.inf), np.inf)
# There are now 6 breakpoints to create 5 groupings:
# array([ -inf, -1.91260048, -0.9230609 , 1.05601827, 2.04555785,
# inf])
labels = ['[-inf,-2]', '(-2,-1]', '(-1,1]', '(1,2]', '(2,inf]']
groups = pd.cut(b, bins=breakpoints, labels=labels)
すべてがここまで良好です。
a.groupby(groups).corrwith(b.groupby(groups))
任意のアイデア:私はValueError
を投げる、.groupby
で.corrwith
を使用して、最後の行にハングアップしていますか? a.corrwith(b)
の結果はシリーズなので、ここでの結果はグループ/バケットを列として持つDataFrameでなければならないと考えています。例えば、1つの列が次のようになります。機能が、かなりありません
print(a[b < breakpoints[1]].corrwith(b[b < breakpoints[1]]))
# Correlation conditional on that `b` is [-inf, -2 stdev]
col0 0.43708
col1 -0.08440
col2 -0.02923
dtype: float64