python - 每个 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 中自动化这个过程?
解决方案
在 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)
应该返回相同的值。
推荐阅读
- python - 如何不签入多个数据框熊猫?
- google-bigquery - 从 gs 加载的 bigquery 中的通配符
- ruby-on-rails - 带有 no_content 返回且没有其他代码的 DoubleRenderError
- html - 如何将svg嵌入svg?
- image-segmentation - 具有密集 vnet 的 niftynet 多类 3D 分割
- node.js - SPFx Webpart - node_modules/@types/ [prop types] 和 [react] index.d.ts:在 gulp 构建时加载“错误 TS1005”
- java - 模拟 Mongo 集合时出现 NullPointerException
- puppeteer - 如何在 puppeteer 中删除添加到表单中的项目
- c++ - ECS序列化
- autodesk-forge - 在 Forge 3D 查看器中将 instanceTree 设置为自定义节点