【问题标题】:How to Read multiple files in Python for Pandas separate dataframes如何在 Python 中为 Pandas 单独的数据框读取多个文件
【发布时间】:2019-07-12 23:46:35
【问题描述】:

我正在尝试将 6 个文件读入 7 个不同的数据帧,但我不知道该怎么做。文件名可以是完全随机的,即我知道文件但它不像data1.csv data2.csv。

我尝试使用这样的东西:

import sys
import os
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
f1='Norway.csv'
f='Canada.csv'
f='Chile.csv'

Norway = pd.read_csv(Norway.csv)
Canada = pd.read_csv(Canada.csv)
Chile = pd.read_csv(Chile.csv )

我需要读取不同数据帧中的多个文件。当我使用一个文件时它工作正常

file='Norway.csv
Norway = pd.read_csv(file)

我得到了错误:

NameError: name 'norway' is not defined

【问题讨论】:

    标签: python-3.x pandas csv


    【解决方案1】:

    您可以将所有 .csv 文件读入一个数据帧。

    for file_ in all_files:
        df = pd.read_csv(file_,index_col=None, header=0)
        list_.append(df)
    
    # concatenate all dfs into one
    big_df = pd.concat(dfs, ignore_index=True)
    

    然后将大数据框拆分为多个(在您的情况下为 7)。例如,-

    import numpy as np
    num_chunks = 3  
    df1,df2,df3 = np.array_split(big_df,num_chunks)
    
    

    希望这会有所帮助。

    【讨论】:

    • 在我的情况下无法合并和拆分,每个帧中的数据可能几乎相等,但我不能冒险,即使一行的差异也会产生差异
    • pd.read_csv() 期望第一个参数为str 类型的文件路径,因此您应该使用Norway = pd.read_csv('<relative file path>')
    • 谢谢,我错过了那里的“文件”,
    • @AbhinavKumar,你说“想将 6 个文件读入 7 个不同的数据帧”。您必须确保,所有 6 个文件中的所有行数组合在一起可以均分为 7。
    • 不,我无法合并和拆分,我需要对 3 个文件执行相同的操作,并对 3 执行一些完全不同的操作。它们包含的信息也相同,但我无法合并到一个数据框中。我希望我听起来很清楚。
    【解决方案2】:

    在谷歌搜索了一段时间后,我决定将不同问题的答案组合成这个问题的解决方案。此解决方案不适用于所有可能的情况。您必须对其进行调整以满足您的所有情况。

    查看解决方案to this question

     # import libraries
    import pandas as pd
    import numpy as np
    import glob
    import os
    # Declare a function for extracting a string between two characters
    def find_between( s, first, last ):
        try:
            start = s.index( first ) + len( first )
            end = s.index( last, start )
            return s[start:end]
        except ValueError:
            return ""
    path = '/path/to/folder/containing/your/data/sets' # use your path
    all_files = glob.glob(path + "/*.csv")
    list_of_dfs = [pd.read_csv(filename, encoding = "ISO-8859-1") for filename in all_files]
    list_of_filenames = [find_between(filename, 'sets/', '.csv') for filename in all_files] # sets is the last word in your path
    # Create a dictionary with table names as the keys and data frames as the values
    dfnames_and_dfvalues = dict(zip(list_of_filenames, list_of_dfs))
    

    【讨论】:

      猜你喜欢
      • 2017-05-11
      • 1970-01-01
      • 2017-03-02
      • 2019-11-23
      • 2018-08-07
      • 2020-12-31
      • 2019-11-18
      • 2019-11-25
      • 1970-01-01
      相关资源
      最近更新 更多