我有以下代码来创建一个带有R的最后一列的图案化上三角矩阵。我想知道是否有人指出更有效的方法来获得相同的。
matrix_k <- function(n){
j <- 0
kn22 <- NULL
while(j < n-1){
long <- sqrt((n-j-1)*(n-j))
i <- 0
kn2 <- NULL
while(i < n){
if(i == j) k = (n-j-1) else k = NA
if(i < j) k = 0 else k = k
if(i > j) k = -1 else k = k
kn <- k/long
kn2 <- cbind(kn2, kn)
i <- i+1
}
kn22 <- rbind(kn22, kn2)
j <- j+1
}
return(kn22)
}
matrix_k(5)
kn kn kn kn kn
[1,] 0.8944272 -0.2236068 -0.2236068 -0.2236068 -0.2236068
[2,] 0.0000000 0.8660254 -0.2886751 -0.2886751 -0.2886751
[3,] 0.0000000 0.0000000 0.8164966 -0.4082483 -0.4082483
[4,] 0.0000000 0.0000000 0.0000000 0.7071068 -0.7071068
答案 0 :(得分:1)
这是一个更快,更紧凑的版本:
df = pd.DataFrame({'A':list('abcde?'),
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':[4,3,5,7,1,'?'],
'E':['?',3,6,'?',2,4]}).astype(str)
print (df)
A B C D E
0 a 4 7 4 ?
1 b 5 8 3 3
2 c 4 9 5 6
3 d 5 4 7 ?
4 e 5 2 1 2
5 ? 4 3 ? 4
#replace only in columns from list
cols = ['C','D','E']
#if only ? with numeric to NaNs
df[cols] = df[cols].replace('?', np.nan).astype(float)
#replace all non numeric to NaNs
#df[cols] = df[cols].apply(lambda x: pd.to_numeric(x, errors='coerce'))
#replace NaNs by means
df = df.fillna(df.mean())
print (df)
A B C D E
0 a 4 7.0 4.0 3.75
1 b 5 8.0 3.0 3.00
2 c 4 9.0 5.0 6.00
3 d 5 4.0 7.0 3.75
4 e 5 2.0 1.0 2.00
5 ? 4 3.0 4.0 4.00