Win*_*erZ 4 python numpy pandas
我有一个大熊猫数据框(97165 行和 2 列),我想计算并保存每 100 行这些列之间的相关性,我想要这样的东西:
第一个相关性 --> 从 0 到 100 的行 --> corr = 0.265
第二个相关性 --> 从 1 到 101 的行 --> corr = 0.279
第三个相关性 --> 从 2 到 102 的行 --> corr = 0.287
每个值都必须存储,然后在图中显示,所以我必须将所有这些值保存在列表或类似的东西中。
我一直在阅读与滚动窗口熊猫滚动窗口相关的熊猫文档, 但我无法实现任何目标。我试图生成一个简单的循环来获得一些结果,但我遇到了内存问题,我尝试过的代码是:
lcl = 100
a = []
for i in range(len(tabla)):
x = tabla.iloc[i:lcl, [0]]
y = tabla.iloc[i:lcl, [1]]
z = x['2015_Avion'].corr(y['2015_Hotel'])
a.append(z)
lcl += 1
Run Code Online (Sandbox Code Playgroud)
有什么建议?
我们可以通过处理数组数据来优化内存和性能。
方法#1
首先,让我们有一个数组解决方案来获取两个1D数组之间对应元素的相关系数。这将基本上受到启发this post并且看起来像这样 -
def corrcoeff_1d(A,B):
# Rowwise mean of input arrays & subtract from input arrays themeselves
A_mA = A - A.mean(-1,keepdims=1)
B_mB = B - B.mean(-1,keepdims=1)
# Sum of squares
ssA = np.einsum('i,i->',A_mA, A_mA)
ssB = np.einsum('i,i->',B_mB, B_mB)
# Finally get corr coeff
return np.einsum('i,i->',A_mA,B_mB)/np.sqrt(ssA*ssB)
Run Code Online (Sandbox Code Playgroud)
现在,要使用它,请使用相同的循环,但在数组数据上 -
lcl = 100
ar = tabla.values
N = len(ar)
out = np.zeros(N)
for i in range(N):
out[i] = corrcoeff_1d(ar[i:i+lcl,0], ar[i:i+lcl,1])
Run Code Online (Sandbox Code Playgroud)
我们可以通过预先计算的滚动平均值为用于计算对性能进一步优化A_mA的corrcoeff_1d有convolution,但首先让我们记忆错误的方式进行。
方法#2
这是一种几乎矢量化的方法,因为我们将对大多数迭代进行矢量化,除了最后没有合适窗口长度的剩余切片。循环计数将从 减少97165到lcl-1ie 仅99。
lcl = 100
ar = tabla.values
N = len(ar)
out = np.zeros(N)
col0_win = strided_app(ar[:,0],lcl,S=1)
col1_win = strided_app(ar[:,1],lcl,S=1)
vectorized_out = corr2_coeff_rowwise(col0_win, col1_win)
M = len(vectorized_out)
out[:M] = vectorized_out
for i in range(M,N):
out[i] = corrcoeff_1d(ar[i:i+lcl,0], ar[i:i+lcl,1])
Run Code Online (Sandbox Code Playgroud)
辅助功能 -
# /sf/answers/2805953671/ @ Divakar
def strided_app(a, L, S ): # Window len = L, Stride len/stepsize = S
nrows = ((a.size-L)//S)+1
n = a.strides[0]
return np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n))
# /sf/answers/2919253641/ @Divakar
def corr2_coeff_rowwise(A,B):
# Rowwise mean of input arrays & subtract from input arrays themeselves
A_mA = A - A.mean(-1,keepdims=1)
B_mB = B - B.mean(-1,keepdims=1)
# Sum of squares across rows
ssA = np.einsum('ij,ij->i',A_mA, A_mA)
ssB = np.einsum('ij,ij->i',B_mB, B_mB)
# Finally get corr coeff
return np.einsum('ij,ij->i',A_mA,B_mB)/np.sqrt(ssA*ssB)
Run Code Online (Sandbox Code Playgroud)
NaN 填充数据的相关性
下面列出了基于 Pandas 的相关计算的 NumPy 解决方案,用于计算一维数组和行相关值之间的相关性。
1) 两个一维数组之间的标量相关值 -
def nancorrcoeff_1d(A,B):
# Get combined mask
comb_mask = ~(np.isnan(A) & ~np.isnan(B))
count = comb_mask.sum()
# Rowwise mean of input arrays & subtract from input arrays themeselves
A_mA = A - np.nansum(A * comb_mask,-1,keepdims=1)/count
B_mB = B - np.nansum(B * comb_mask,-1,keepdims=1)/count
# Replace NaNs with zeros, so that later summations could be computed
A_mA[~comb_mask] = 0
B_mB[~comb_mask] = 0
ssA = np.inner(A_mA,A_mA)
ssB = np.inner(B_mB,B_mB)
# Finally get corr coeff
return np.inner(A_mA,B_mB)/np.sqrt(ssA*ssB)
Run Code Online (Sandbox Code Playgroud)
2) 两个2D数组之间的行相关性(m,n)给我们一个1D形状数组(m,)-
def nancorrcoeff_rowwise(A,B):
# Input : Two 2D arrays of same shapes (mxn). Output : One 1D array (m,)
# Get combined mask
comb_mask = ~(np.isnan(A) & ~np.isnan(B))
count = comb_mask.sum(axis=-1,keepdims=1)
# Rowwise mean of input arrays & subtract from input arrays themeselves
A_mA = A - np.nansum(A * comb_mask,-1,keepdims=1)/count
B_mB = B - np.nansum(B * comb_mask,-1,keepdims=1)/count
# Replace NaNs with zeros, so that later summations could be computed
A_mA[~comb_mask] = 0
B_mB[~comb_mask] = 0
# Sum of squares across rows
ssA = np.einsum('ij,ij->i',A_mA, A_mA)
ssB = np.einsum('ij,ij->i',B_mB, B_mB)
# Finally get corr coeff
return np.einsum('ij,ij->i',A_mA,B_mB)/np.sqrt(ssA*ssB)
Run Code Online (Sandbox Code Playgroud)