2017-08-31 8 views
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 

答えて

0

一つの解決策:

full = a.join(b.to_frame(name='_drop')) 
corrs = (full.groupby(groups) 
     .corr() 
     .loc[(slice(None), a.columns), '_drop'] 
     .unstack() 
     .T) 

print(corrs) 
     [-inf,-2] (-2,-1] (-1,1] (1,2] (2,inf] 
col0 0.43708 0.06716 0.02437 0.01695 0.05384 
col1 -0.08440 0.04208 0.05529 -0.07146 0.14766 
col2 -0.02923 -0.19672 0.01519 -0.02290 -0.17101 
関連する問題