为了账号安全,请及时绑定邮箱和手机立即绑定

来自 csv 文件的 Python 总和

来自 csv 文件的 Python 总和

侃侃尔雅 2022-07-19 10:25:57
我有 133 个 CSV 文件第一个文件 file1.cvs 有以下数据:A               b    CName            2   Valuejack            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.csvjack  4.442%sara  13%tom   1%    File name : file2.csv.......ETC使用任何编程语言(python、ruby、r 等)
查看完整描述

2 回答

?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

使用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)

})


查看完整回答
反对 回复 2022-07-19
?
婷婷同学_

TA贡献1844条经验 获得超8个赞

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")


查看完整回答
反对 回复 2022-07-19
  • 2 回答
  • 0 关注
  • 112 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号