You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将观测计数转换为对称交叉表(Crosstab)?

转换长格式聚类数据为对称交叉表

方法一:使用R语言

  1. 先把你的数据读入成数据框:
df <- data.frame(
  Cluster.x = c(1,1,2,2,2),
  Cluster.y = c(4,7,1,4,7),
  n = c(8,1,2,4,1)
)
  1. 提取所有出现过的聚类编号,排序后作为交叉表的行和列:
all_clusters <- sort(unique(c(df$Cluster.x, df$Cluster.y)))
  1. 创建一个空的对称矩阵,初始值全为0:
sym_matrix <- matrix(0, nrow = length(all_clusters), ncol = length(all_clusters),
                     dimnames = list(all_clusters, all_clusters))
  1. 填充矩阵的对称位置:
for (i in 1:nrow(df)) {
  x <- as.character(df$Cluster.x[i])
  y <- as.character(df$Cluster.y[i])
  sym_matrix[x, y] <- df$n[i]
  sym_matrix[y, x] <- df$n[i]
}
  1. 把对角线的值设为0(交叉表对角线无实际意义):
diag(sym_matrix) <- 0

最后输出的sym_matrix就是目标对称交叉表,和示例格式完全一致。

方法二:使用Python Pandas

  1. 导入pandas并构造数据:
import pandas as pd

df = pd.DataFrame({
    'Cluster.x': [1,1,2,2,2],
    'Cluster.y': [4,7,1,4,7],
    'n': [8,1,2,4,1]
})
  1. 获取所有唯一聚类标签并排序:
all_clusters = sorted(set(df['Cluster.x']).union(set(df['Cluster.y'])))
  1. 创建全0的对称DataFrame:
sym_crosstab = pd.DataFrame(0, index=all_clusters, columns=all_clusters)
  1. 遍历数据填充对称位置:
for _, row in df.iterrows():
    x = row['Cluster.x']
    y = row['Cluster.y']
    sym_crosstab.loc[x, y] = row['n']
    sym_crosstab.loc[y, x] = row['n']
  1. 对角线设为0:
for cluster in all_clusters:
    sym_crosstab.loc[cluster, cluster] = 0

打印sym_crosstab即可得到符合要求的对称交叉表。

内容的提问来源于stack exchange,提问作者craszer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 21:15:44