【问题标题】:Python total sum from a csv file来自 csv 文件的 Python 总和
【发布时间】:2020-05-21 13:59:53
【问题描述】:

我有 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 等)

【问题讨论】:

  • 我猜试试 pandas read_csv
  • 使用python 可能很容易完成,特别是具有DataFrame 功能的pandas 模块。见here

标签: python r excel database csv


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 从文件的外观来看,您应该在 read.csv 部分设置skip = 2,这样它就会跳过文件的前两行。然后,您应该将变量NameValue 更改为数据的实际名称,例如Node.NameVirtual.Memory。您可以使用colnames(df) 检查R 如何导入数据的列名。
    • 谢谢我今天只需要找到解决方案抱歉问了很多问题:(我现在收到这个错误:> source("C:\\Users\\dell\\Desktop\\12.R ") Summary.factor(c(2L, 2L, 3L, 3L, 3L, 6L), na.rm = FALSE) 中的错误:'sum' 对因子没有意义
    • 可能是因为你的数据有“%”号。您可以在创建结果对象之前将其删除,使用 stringr 包,例如:df$Value&lt;-str_extract(df$Value,"(\\d)+")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 2018-07-27
    • 1970-01-01
    • 2021-08-20
    • 2021-01-10
    • 2017-01-21
    • 2016-09-07
    相关资源
    最近更新 更多