将列名(年)转换为变量值 - Python,R

时间:2014-10-21 06:01:09

标签: python r pandas

我的CSV看起来像这样:

                       1991       1992      1993       1991       1992      1993
VariableA  VariableB   VariableC  VariableC VariableC  VariableD  VariableD VariableD
     lm          mt         1          3          4            2        3         5

所以我想创建一个名为year的变量并执行以下操作:

VariableA VariableB     Year   VariableC   VariableD 
 lm          mt         1991      1            2
 lm          mt         1992      3            3
 lm          mt         1993      4            5

我主要使用Pandas,我正在学习,但我不知道正确读取数据,然后进行操作。如果有人在R中提出解决方案,那也会很好。

EDITION:

我的真实数据框架是从1991年到2013年的多年,并且有更多变量具有重复。我使用Ananda Mahto建议的包splitstackshape尝试了代码inr R,但是我收到了一条错误消息。那么,我的错误是什么?

mydf <- read.csv("DatosCOMPUSTATfinal.csv", skip = 3, check.names = FALSE)

nombres <- names(mydf)[-c(1,2,3)]

nombres <- unique(nombres)

> nombres
 [1] "Employees"                  "Market Value-daily"        
 [3] "Market to book - daily"     "Total return"              
 [5] "Total assets"               "total stockholders' equity"
 [7] "Sales"                      "EBITDA"                    
 [9] "EBIT"                       "Pretax income"             
[11] "Income (loss)"             

> names(mydf[c(1,2,3)])
    [1] "Company name"            "employer identification"
    [3] "CUSIP"     

names(mydf)[-c(1,2,3)] <- paste(names(mydf)[-c(1,2,3)], 
                               c(1991:2013), sep = "_")


nv <- merged.stack(mydf, id.vars = names(mydf[c(1,2,3)]) , var.stubs = nombres , sep = "_" )

然后,我收到错误消息:

Error in if (ncol(x) == 1L) { : argument is of length zero

第2版:

我用reshape函数尝试了这段代码,但收到了“内存耗尽”的消息。我不知道为什么,因为数据框只是改变它的方向,它的大小小于15 mb。为什么会发生这种情况?我该如何处理?

newmydf <- reshape(mydf, direction = "long", idvar = 1:3, varying = 4:ncol(mydf), sep = "_")
Error: memory exhausted (limit reached?)

2 个答案:

答案 0 :(得分:7)

在R中,一种方法可能是读取跳过第一行的csv,将其作为变量名称的一部分添加回来,然后使用reshape获取所需的输出。

尝试以下内容:

mydf <- read.csv("yourfile.csv", skip = 1, check.names = FALSE)
names(mydf)[-c(1, 2)] <- paste(names(mydf)[-c(1, 2)], 
                               c(1991, 1992, 1993), sep = "_")
reshape(mydf, direction = "long", idvar = 1:2, 
        varying = 3:ncol(mydf), sep = "_")
#            VariableA VariableB time VariableC VariableD
# lm.mt.1991        lm        mt 1991         1         2
# lm.mt.1992        lm        mt 1992         3         3
# lm.mt.1993        lm        mt 1993         4         5

重命名步骤后,如果reshape()对您来说太慢,请尝试使用我的“splitstackshape”软件包中的merged.stack

library(splitstackshape)
merged.stack(mydf, var.stubs = c("VariableC", "VariableD"), sep = "_")
#    VariableA VariableB .time_1 VariableC VariableD
# 1:        lm        mt    1991         1         2
# 2:        lm        mt    1992         3         3
# 3:        lm        mt    1993         4         5

答案 1 :(得分:1)

R中的另一种方法是在使用dplyr/tidyr读取数据集之后使用read.csv(对于大数据集会更快),如@Ananda Mahto的帖子中所述

 library(dplyr)
 library(tidyr)

  mydf %>% 
       gather(Var, Val, matches("[0-9]+$")) %>% 
       separate(Var, c("Var", "Year")) %>%
       spread(Var, Val)

  #  VariableA VariableB Year VariableC VariableD
  #1        lm        mt 1991         1         2
  #2        lm        mt 1992         3         3
  #3        lm        mt 1993         4         5

数据

 mydf <- structure(list(VariableA = structure(1L, .Label = "lm", class = "factor"), 
VariableB = structure(1L, .Label = "mt", class = "factor"), 
VariableC_1991 = 1L, VariableC_1992 = 3L, VariableC_1993 = 4L, 
VariableD_1991 = 2L, VariableD_1992 = 3L, VariableD_1993 = 5L), .Names = c("VariableA", 
"VariableB", "VariableC_1991", "VariableC_1992", "VariableC_1993", 
"VariableD_1991", "VariableD_1992", "VariableD_1993"), class = "data.frame", row.names = c(NA, 
-1L))