【问题标题】:Navigate and append csv from child directories从子目录导航和附加 csv
【发布时间】:2019-04-05 20:42:11
【问题描述】:

我在一个包含 36 个不同文件夹的目录中。每个文件夹中都有一个 csv。我想将它们中的每一个附加在一起以在 python 中创建一个大数据框。

在 R 中,我会这样做:

cwd = getwd() #get current directory
fil = list.files() #get list of all files/folders in the directory
Bigdf = NULL #initialize empty df
for(i in fil){ #read through all folders in current directory
    setwd(paste0(cwd,'/',i)) #navigate to i'th folder
    fil2 = list.files() #get list of files in i'th folder
    for(j in fil2){
        a = read.csv(paste0(cwd,'/',i,'/',j)) #read in all csv's 
        Bigdf = rbind(Bigdf,a[,c(2,4:11)]) #append desired columns to data frame
    }
    setwd(cwd) 
}

我将如何在 python 中做这样的事情?

我尝试实现How can I read the contents of all the files in a directory with pandas?How do I list all files of a directory?,但无济于事。我想我遗漏了一些明显的东西,希望有人能指出我正确的方向。

【问题讨论】:

  • 您可能想看看模块os(例如os.listdir)和csv
  • 就是这样,谢谢指导

标签: python r dataframe navigation


【解决方案1】:
import glob
import pandas as pd

li =[]

for filename in glob.iglob('src/**/*.csv', recursive=True):
    df = pd.read_csv(filename, index_col=None, header=0)
    li.append(df)

frame = pd.concat(li, axis=0, ignore_index=True)

组合

Import multiple csv files into pandas and concatenate into one DataFrame

How to use glob() to find files recursively?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-19
    • 2016-12-08
    • 2021-01-07
    • 1970-01-01
    • 2010-12-06
    • 2016-07-09
    • 2018-10-13
    • 2011-10-27
    相关资源
    最近更新 更多