在每个字符串中标记(拆分?)数据集的最佳方法
The best way to mark (split?) dataset in each string
我有一个包含 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 是我最喜欢的...
Pandas could load this using 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
这将为您提供一个数据框,允许您出于任何需要访问每个单独的列
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)
在 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
参数。
在 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)]
我有一个包含 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 是我最喜欢的...
Pandas could load this using 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
这将为您提供一个数据框,允许您出于任何需要访问每个单独的列
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)
在 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
参数。
在 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)]