繁体   English   中英

来自csv文件的Python总和

[英]Python total sum from a csv file

我有 133 个 CSV 文件

第一个文件 file1.cvs 有以下数据:

A               b    C
Name            2   Value
jack            3   2%
jack            3   1.33%
jack            4   1.112%
sara            5   4%
sara            6   9%
adam            1   7%
adam            2   10%
nada            3   3%
nada            4   1%
tom             5   1%

我想计算列(仅限 jack、sara、tom)和 C 列上特定名称的总和,并将输出保存在新的 csv 文件中,如下所示:

File name : file1.csv
jack  4.442%
sara  13%
tom   1%    

File name : file2.csv

.......等等

使用任何编程语言( python 、 ruby​​ 、 r 等..)

1.创建可重现的最小示例数据

df <- data.frame(A=rep(c("Jack", "Joe"), 3), C=runif(6))

2.使用dplyr库的解决方案:

library(dplyr)
summarised <- df %>% 
  group_by(A) %>% 
  summarise(Total = sum(C))

write.csv(summarised, "File_Name.csv")

使用R你可以先搜索所有包含在一个文件夹中的CSV文件,然后做一个sapply超过该矢量(使用dplyr包来执行所需的操作)。 最后,在list.files指示的同一文件夹中搜索结果文件。

library(dplyr)

#Find all the csv files in the indicated path
#Change the path location to the folder where you have your csv files
file_locs<-list.files(path="C:/Folder with csvs",
                      pattern = ".csv",
                      full.names = T)

sapply(file_locs, function(x){

  #Read csv, skipping first line if it contains the A, b, c entries
  #as headers, if not you can remove the "skip = 1"
  df<-read.csv(x, skip = 1)

  #Use dplyr to get the Value sum, grouped by Name
  resuls<-df %>%
    group_by(Name) %>%
    summarize(sumVal = sum(Value))

  #Get the csv original name, i.e., without the .csv part
  file_name<-strsplit(x,".csv")[[1]][1]

  #Write the results using the original file name and adding: _resul
  write.csv(resuls, paste0(file_name,"_resul.csv"),row.names = F)
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM