簡體   English   中英

在python熊貓中讀取和合並過去14天的csv文件

[英]Read and concat csv files from past 14 days in python pandas

我需要編寫一個腳本來讀取過去14天(每天每天)中具有特定名稱的所有csv文件,但是當我進行concat操作時,這會給我一個小立方體(在jupyter-notebook中),並且該符號沒有任何內容。

def get_local_file(pdate, hour, path='/data/'):
        """Get date+hour processing file from local drive

       :param pdate: str Processing date
        :param hour: str Processing hour
        :param path: str Path to file location
        :return: Pandas DF Retrieved DataFrame
        """

        sdate = pdate + '-' + str(hour)
        for p_file in os.listdir(path):
            if fnmatch.fnmatch(p_file, 'ABC_*'+sdate+'*.csv'):
                return path+p_file

def get_files(pdate, path='/data/'):
    hours = [time(i).strftime('%H') for i in range(24)]
    fileList=[]
    for hour in hours:
        fileList.append(get_local_file(pdate, hour))
    return fileList

end_datetime = datetime.combine(date.today(), time(0, 0, 0))
proc_datetime = end_datetime - timedelta(days=14)
while proc_datetime <= end_datetime:
    proc_datetime += timedelta(days=1)
    a = get_files(str(proc_datetime.date()).replace('-', '_'))
    frame = pd.DataFrame()
    list_ = []
    for file_ in a:
        if file_ != None:
            df = pd.read_csv(file_,index_col=None, header=0, delimiter=';')
            list_.append(df)
            frame = pd.concat(list_)

我敢肯定,可以從while循環及其下面簡化代碼,但不知道如何做。

如果要從一堆.csv文件創建單個數據框,則可以通過以下方式進行操作:

  • 在循環之前初始化一個空列表
  • 遍歷文件,對於數據幀中的每一次讀取,並將其附加到列表中
  • 循環后將列表連接到單個數據幀中

我沒有檢查您對日期和文件名的處理是否正確,但是以下是有關串聯部分的代碼的相關更改:

end_datetime = datetime.combine(date.today(), time(0, 0, 0))
proc_datetime = end_datetime - timedelta(days=14)
list_ = []
while proc_datetime <= end_datetime:
    proc_datetime += timedelta(days=1)
    a = get_files(str(proc_datetime.date()).replace('-', '_'))
    for file_ in a:
        if file_ != None:
            df = pd.read_csv(file_, index_col=None, header=0, delimiter=';')
            list_.append(df)
frame = pd.concat(list_)
import pandas
import glob
csvFiles = glob.glob(path + "/data/*.csv")
list_ = []
for file in csvFiles:
    if ((datetime.combine(date.today(), time(0, 0, 0)) - datetime(*map(int, file.split("-")[1].split("_")))).days < 14)
        df = pandas.read_csv(file, index_col=None, header=0, delimiter=';')
        list_.append(df_f)
frame = pandas.concat(list_, ignore_index=True)
frame.to_csv("Appended File.csv")

假定文件路徑中沒有任何連字符(-)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM