![](/img/trans.png)
[英]pandas: how to compute correlation of between one column with multiple other columns?
[英]Pandas Correlation One Column to Many Columns Group by range of the column
使用下面的簡單數據框:
df= pd.DataFrame({'v1': [1, 3, 2, 1, 6, 7],
'v2': [2, 2, 4, 2, 4, 4],
'v3': [3, 3, 2, 9, 2, 5],
'v4': [4, 5, 1, 4, 2, 5]})
(第一種解釋)獲得一個變量與其他列的相關性的一種方法是:
correlations = df.corr().unstack().sort_values(ascending=False) # Build correlation matrix
correlations = pd.DataFrame(correlations).reset_index() # Convert to dataframe
correlations.columns = ['col1', 'col2', 'correlation'] # Label it
correlations.query("col1 == 'v2' & col2 != 'v2'") # Filter by variable
# output of this code will give correlation of column v2 with all the other columns
(第二種解釋)在按列 v2 分組后獲得列 v1 與列 v3、v4 相關性的一種方法是使用這一行:
df.groupby('v2')[['v1', 'v3', 'v4']].corr().unstack()['v1']
在您的情況下,v2 是“Signal_Up”,v1 是“信號”,v3、v4 列代理“Net_return_at_t_plusX”列。
我可以通過使用“groupby”函數按 Signal_Up 列的各個類別獲得相關性。 但是,我無法將“corr”函數應用於兩列以上。
所以,我不得不使用“concat”函數來組合所有這些。
`a = df.groupby('Signal_Up')[['signal,'Net_return_at_t_plus1']].corr().unstack().iloc[:,1]
b = df.groupby('Signal_Up')[['signal','Net_return_at_t_plus5']].corr().unstack().iloc[:,1]
c = df.groupby('Signal_Up')[['signal','Net_return_at_t_plus10']].corr().unstack().iloc[:,1]
dfCorr = pd.concat([a, b, c], axis=1)`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.