在每个字符串

时间:2015-04-22 14:02:52

标签: python r string split dataset

我有一个包含485k字符串(1.1 GB)的数据集。 每个字符串包含大约700个字符,其中包含大约250个变量(每个变量1-16个字符),但它没有任何分割标记。每个变量的长度是已知的。按符号,修改和标记数据的最佳方法是什么?

例如: 我有类似的字符串:

0123456789012...
1234567890123...    

和长度数组: 5,3,1,4,... 那我应该这样:

01234,567,8,9012,...
12345,678,9,0123,...

有人可以帮我吗? Python或R-tools主要是我的首选......

4 个答案:

答案 0 :(得分:1)

Pandas可以使用read_fwf加载:

In [321]:

t="""0123456789012..."""
pd.read_fwf(io.StringIO(t), widths=[5,3,1,4], header=None)
Out[321]:
      0    1  2     3
0  1234  567  8  9012

这将为您提供一个数据框,允许您出于任何目的访问每个列

答案 1 :(得分:1)

在R read.fwf中可行:

# inputs
x <- c("0123456789012...", "1234567890123... ")
widths <- c(5,3,1,4)

read.fwf(textConnection(x), widths, colClasses = "character")

,并提供:

     V1  V2 V3   V4
1 01234 567  8 9012
2 12345 678  9 0123

如果需要数字而不是字符列,则删除colClasses参数。

答案 2 :(得分:1)

在R:

中试试
x <- "0123456789012"

y <- c(5,3,1,4)

output <- paste(substring(x,c(1,cumsum(y)+1),cumsum(y)),sep=",")
output <- output[-length(output)]

答案 3 :(得分:0)

R中的一个选项是

indx1 <- c(1, cumsum(len)[-length(len)]+1)
indx2 <- cumsum(len)
toString(vapply(seq_along(len), function(i)
         substr(str1, indx1[i], indx2[i]), character(1)))
#[1] "01234, 567, 8, 9012"

数据

str1 <- '0123456789012'
len <- c(5,3,1,4)