数据整理-将n步列转换为n行

时间:2019-05-14 12:09:55

标签: r python-3.x vba

我需要以下帮助。任何Python,R或VBA代码都会有很大帮助

输入

Name    Age Grade   Name    Age Grade   Name    Age Grade
Esther  12  A   Carol   15  A   Eugene  15  C
Isaac   17  B   Kelvin  21  C   Claire  17  B

所需的输出

Name    Age Grade                       
Esther  12  A                       
Carol   15  A                       
Eugene  15  C                       
Isaac   17  B                       
Kelvin  21  C                       
Claire  17  B

2 个答案:

答案 0 :(得分:0)

R中,一种选择是通过列名和splitunlist

data.frame(lapply(split.default(df1, names(df1)), unlist))

或者另一个选择是melt中的data.table

library(data.table)
melt(setDT(df1), measure = patterns("^Name", "^Age", "^Grade"), 
       value.name = c("Name", "Age", "Grade"))[, variable := NULL][]
#      Name Age Grade
#1: Esther  12     A
#2:  Isaac  17     B
#3:  Carol  15     A
#4: Kelvin  21     C
#5: Eugene  15     C
#6: Claire  17     B

答案 1 :(得分:0)

对于,请尝试以下

Sub transpdata()

Dim LCol As Long, LRowSource As Long, LRowDest As Long, i As Long
Dim src As Worksheet, dst As Worksheet

Set src = Sheet3 'Change source data wb & ws reference
Set dst = Sheet1 'Change destination data wb & ws reference

With src

    LRowSource = src.Cells(src.Rows.Count, "A").End(xlUp).Row + 1
    LCol = .Cells(1, .columns.Count).End(xlToLeft).Column

    For i = 1 To LCol Step 3
        LRowDest = dst.Cells(dst.Rows.Count, "A").End(xlUp).Row + 1
        dst.Range(dst.Cells(LRowDest, 1), dst.Cells(LRowDest + LRowSource - 2, 3)).Value = .Range(.Cells(2, i), .Cells(LRowSource, i + 2)).Value
    Next i

    dst.Range("A1:C1").Value = Array("Name", "Age", "Grade")

End With

End Sub