python - 如何从csv中的多个文件计算平均值
问题描述
在 python 中使用这个选项可以计算多个 csv 文件的平均值
如果 file1.csv 到 file100.csv 都在同一个目录中,你可以使用这个 Python 脚本:
#!/usr/bin/env python3
N = 100
mean_sum = 0
std_sum = 0
for i in range(1, N + 1):
with open(f"file{i}.csv") as f:
mean_sum += float(f.readline().split(",")[1])
std_sum += float(f.readline().split(",")[1])
print(f"Mean of means: {mean_sum / N}")
print(f"Mean of stds: {std_sum / N}")
怎么可能在 R 中实现它?
解决方案
“一切都可以编码”,埃里克 :)
如果您不提供最小的可重现示例并描述您迄今为止尝试的内容以及您的问题所在,那么很难提供帮助。
以下是基于{tidyverse}
; 一组可以很好地协同工作的软件包。我写的差不多pseudo-code
应该能让你继续前进。显然,您将不得不适应、重命名以适合您的项目/变量名称等。
祝你好运:
library(readr) # package to read tabular data
library(dplyr) # main working horse to crunch data
library(purrr) # functional programming for iterations/loops
pth <- "my-data-folder" # provide path to your data
# create a list of file names in your folder
## you may need to fine-tune the regular pattern to select the files you look for
## full.names gives you the path/name of your data files
## \\.csv is the way to "escape" the dot of the csv type ending
fns <- list.files(path = pth, pattern = "*file.*\\.csv", full.names = TRUE)
# write a function that reads the file and calculates your stats
## you can "summarise" stats over a table
my_function <- function(.fn){
df <- read_csv(.fn) # read the file
df <- df %>%
summarise(MEAN = mean(my-target-variable) # calc mean of your file/data
, SD = sd(my-target-variable) # calc sd of the data
}
# iterate with purrr::map := take list of filenames and apply your function to each list entry
## map_dfr() provides a data frame, you can use "only" map() to get a list
## for testing purposes you can truncate the list of filenames with fns[1:3] for the
## first 3 files, other
ds <- fns %>%
purrr::map_dfr(.f = my_function)
ds
ds
是一个包含 MEAN 和 SD 列的表。
推荐阅读
- javascript - DeviceOrientationEvent.askPermission() 没有提示任何内容
- java - 如何使用 Gradle Java API 6.1.1
- angular - 表单组,表单数组
- input - UWP TextBox 聚焦但无法输入
- mongodb - MongoDB | 推入数组内对象的特定索引内的数组
- amazon-web-services - 如何比较两个 Amazon RDS 快照?
- debian - linstalling libc6:amd64 会破坏语言环境,并且不允许取消配置
- apache-spark - 使用 Pyspark 更新 Dataframe 列中的 Minute 和 Seconds 值
- r - 在平行坐标图上为每个变量添加一条平均线
- google-bigquery - 当源表具有多行表键时,MERGE 中的大查询问题