首页 > 解决方案 > 每个 csv 文件除以引用自不同 csv 文件的特定值以进行规范化

问题描述

我有一个文件夹包含多个要处理的 csv 文件 (target_csv),以及一个不同的 csv 文件来引用行中的特定值 (reference_csv)。

我想做的是从文件夹中读取第一个 target_csv 文件并除以 reference_csv 第一行中的值并保存为新的 csv 文件。然后,重复直到结束(读取第二个 target_csv,它将除以 reference_csv 第二行中的值)。

如果我一一进行,脚本如下所示(这在 R 中有效)。

d1 <- read.table("target1.csv", header=TRUE, sep=',')
d12 <- d1[,2:25]
d13 <- as.matrix(d12)

dref <- read.table("reference.csv", header=TRUE, sep=',')
dref1 <- dref[1,1] #refer first row

d14 <- d13/dref1
write.csv(d14, "normalized1.csv", quote=FALSE, rownames=FALSE)

#Then, repeat as
#d2 <- read.table("target2.csv", header=TRUE, sep=',')
#d22 <- d2[,2:25]
#d23 <- as.matrix(d22)

#dref2 <- dref[1,2] #refer second row

#d24 <- d23/dref2
write.csv(d24, "normalized2.csv", quote=FALSE, rownames=FALSE)

谁能告诉我如何在 R、python 或 linux 中自动化这个过程?

标签: pythonrlinuxloopscsv

解决方案


在 R 中,您可以尝试此选项 -

dref <- read.csv("reference.csv")
#Get the values to divide in a vector
vec <- unlist(d1[1,2:25])

#Name of the target files
filenames <- list.files(pattern = 'target.*csv$')

#Read each file and divide by corresponding vector.
Map(function(x, y) {
  tmp <- read.csv(x)
  write.csv(tmp/y, sub('target', 'normalized', x), quote=FALSE, rownames=FALSE)
}, filenames, vec)

您可以执行的一项检查是length(vec)并且length(filenames)应该返回相同的值。


推荐阅读