python - 在 R 与 Python 中 reshape 数据

标签 python r reshape

我正尝试在 R 中为 k-means 重构数据框。目前数据的结构如下:

 Subject Posture   s1 s2 s3....sn
  1       45       45 43 42 ...
  2       90       35  45 42 ..   
  3        0        3   56 98
  4        45       ....

等等。我想将所有 sn 变量折叠到一个列中,并创建一个带有 s 编号的附加变量:

 Subject Posture sn dv 
 1       45       1 45 
 2       90       2 35    
 3        0       3  31 
 4        45      4  45

这在 R 中是否可行,还是我最好直接在 python 中 reshape csv? 非常感谢任何帮助。

最佳答案

这是 base R 中的典型方法(尽管使用“reshape2”可能是更典型的做法)。

假设我们从“mydf”开始,定义为:

mydf <- data.frame(Subject = 1:3, Posture = c(45, 90, 0),  
    s1 = c(45, 35, 3), s2 = c(43, 45, 56), s3 = c(42, 42, 98))

你可以 reshape :

reshape(mydf, direction = "long", idvar=c("Subject", "Posture"), 
        varying = 3:ncol(mydf), sep = "", timevar="sn")
#        Subject Posture sn  s
# 1.45.1       1      45  1 45
# 2.90.1       2      90  1 35
# 3.0.1        3       0  1  3
# 1.45.2       1      45  2 43
# 2.90.2       2      90  2 45
# 3.0.2        3       0  2 56
# 1.45.3       1      45  3 42
# 2.90.3       2      90  3 42
# 3.0.3        3       0  3 98

关于python - 在 R 与 Python 中 reshape 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22002630/

相关文章:

r - 在R中按组转置数据

r - 在 R 中部分转置数据帧

python - 如何在 x 轴上以小时和分钟格式显示所有 x 值的标签

c# - Python 到 C# 移植后的错误计算

c++ - 如何使用 RcppEigen 在 C 代码中编译函数

r - 使用 purrr::map2 (?) 向数据框添加新列

r - 具有重复列名的整洁 data.frame

python - 单词和字母列表到字母列表

python - "command not found"使用 python 在 os.system 参数中使用行

r - 结合 R Markdown 和动画包