gpt4 book ai didi

python - 转换为 FEATHER 文件会创建巨大的文件

转载 作者:行者123 更新时间:2023-12-02 01:46:39 24 4
gpt4 key购买 nike

我正在尝试将 .rds file进入.feather file用于在 Python 中使用 Pandas 进行阅读。

library(feather)

# Set working directory
data = readRDS("file.rds")
data_year = data[["1986"]]

# Try 1
write_feather(
data_year,
"data_year.feather"
)

# Try 2
write_feather(
as.data.frame(as.matrix(data_year)),
"data_year.feather"
)

Try 1 返回错误:“x”必须是数据框Try 2 实际上写入一个 *.feather 文件,但该文件一年的大小为 4.5GB,而原始 *.rds 文件的几年大小为 0.055GB。

如何将每年的文件转换为单独或非单独的 *.feather 文件,同时保持足够的文件大小?

enter image description here

数据看起来像这样:

enter image description here

data_year 看起来像这样:

enter image description here

*更新

我愿意接受任何有关使数据可在 NumPy/Pandas 中使用同时保持适度文件大小的建议!

最佳答案

也许像下面的函数会有所帮助。

该函数将稀疏矩阵 reshape 为长格式,消除其中的零。这将减少最终的 data.frame 大小和磁盘文件大小。

library(Matrix)
library(feather)

dgcMatrix_to_long_df <- function(x) {
res <- NULL
if(nrow(x) > 0L) {
for(i in 1:nrow(x)){
d <- as.matrix(x[i, , drop = FALSE])
d <- as.data.frame(d)
d$row <- i
d <- tidyr::pivot_longer(d, cols = -row, names_to = "col")
d <- d[d$value != 0,]
res <- rbind(res, d)
}
}
res
}

y <- dgcMatrix_to_long_df(data_year)
head(y)
## A tibble: 6 x 3
# row col value
# <int> <chr> <dbl>
#1 1 Col_0103 51
#2 1 Col_0149 6
#3 1 Col_0188 5
#4 1 Col_0238 89
#5 1 Col_0545 14
#6 1 Col_0547 58


path <- "my_data.feather"
write_feather(y, path)
z <- read_feather(path)
identical(y, z)
#[1] TRUE

# The file size is 232 KB though the initial matrix
# had 1 million elements stored as doubles,
# for a total of 8 MB, a saving of around 97%
file.size(path)/1024
#[1] 232.0234

编辑

下面的函数要快得多。

dgcMatrix_to_long_df2 <- function(x) {
res <- NULL
if(nrow(x) > 0L) {
for(i in 1:nrow(x)){
d <- as.matrix(x[i, , drop = FALSE])
inx <- which(d != 0, arr.ind = TRUE)
d <- cbind(inx, value = c(d[d != 0]))
d[, "row"] <- i
res <- rbind(res, d)
}
}
as.data.frame(res)
}

system.time(y <- dgcMatrix_to_long_df(data_year))
# user system elapsed
# 7.89 0.04 7.92
system.time(y <- dgcMatrix_to_long_df2(data_year))
# user system elapsed
# 0.14 0.00 0.14

测试数据

set.seed(2022)
n <- 1e3
x <- rep(0L, n*n)
inx <- sample(c(FALSE, TRUE), n*n, replace = TRUE, prob = c(0.99, 0.01))
x[inx] <- sample(100, sum(inx), replace = TRUE)
data_year <- Matrix(x, n, n, dimnames = list(NULL, sprintf("Col_%04d", 1:n)))

关于python - 转换为 FEATHER 文件会创建巨大的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70811880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com