如何提取 DateTimeIndex 以在新列中使用? (How do I extract a DateTimeIndex for use in a new column?)


問題描述

如何提取 DateTimeIndex 以在新列中使用? (How do I extract a DateTimeIndex for use in a new column?)

我已從一組 Excel 文件中的文件名中提取日期到 DateTimeIndex 對象列表中。我現在需要將每個提取的日期寫入我從每個 Excel 工作表創建的數據框的新日期列。我的代碼的工作原理是將新的“日期”列寫入每個數據幀,但我無法將對像從它們的生成器對象 DateTimeIndex 格式轉換為 %Y‑%m‑%d 格式。

鏈接到從文件名創建 DateTimeIndexes 列表的代碼:如何將 datefinder 輸出轉換為列表?

將每個列表條目寫入從電子表格創建的每個數據框中的新“日期”列的代碼:

Date' 列,而且它是有用的 '%Y‑%m‑%d' 格式,在數據幀中是有意義的。非常感謝任何幫助。


參考解法

方法 1:

  1. force evaluation with a one line loop like dates = [_ for _ in matches]
  2. convert the index to a column using the .index (or .reset_index() if you don't need to keep it)
  3. convert the column to datetime using pd.to_datetime() . use the .dt.date object of the datetime column to convert to Y‑m‑d

  4. </ol>

    Here's a sample

    import datefinder
    import pandas as pd
    
    data = '''Your appointment is on July 14th, 2016 15:24. Your bill is due 05/05/2016 16:00'''
    matches = datefinder.find_dates(data)
    # force evaluation with 1 line loop
    dates = [_ for _ in matches] # 'dates = list(matches)' also works
    df = pd.DataFrame({'dt_index':dates,'value':['appointment','bill']}).set_index('dt_index')
    df['date'] = df.index
    df['date'] = pd.to_datetime(df['date'])
    df['date'] = df['date'].dt.date
    df
    

    which gives

    value   date
    dt_index        
    2016‑07‑14 15:24:00 appointment 2016‑07‑14
    2016‑05‑05 16:00:00 bill    2016‑05‑05
    

    Edit: Edited to account for forced evaluation

    方法 2:

    A minor fix got it working, I was just trying to carry out too much at once and overthinking it.

    #create empty list and append each date 
    event_dates_transfer = []
    #use .strftime('%Y‑%m‑%d') method on event_dates_dto here if you wish to return a string instead of a datetimeindex
    for i in range(0,len(event_dates_dto)):
        event_dates_transfer.append(event_dates_dto[i][0])
    
    #Create a 'Date' column for each dataframe correlating to the filename it was created from and set it as the index
    for i in range(0, len(df)):
        new_date = event_dates_transfer[i]
        df[i]['Date'] = new_date
        df[i].set_index('Date', inplace=True)
    

    (by NaeblisrhedakNaeblis)

    參考文件

    1. How do I extract a DateTimeIndex for use in a new column? (CC BY‑SA 2.5/3.0/4.0)

#Python #excel #pandas






相關問題

如何從控制台中導入的文件中訪問變量的內容? (How do I access the contents of a variable from a file imported in a console?)

在 python 3.5 的輸入列表中添加美元符號、逗號和大括號 (Adding dollar signs, commas and curly brackets to input list in python 3.5)

為 KeyError 打印出奇怪的錯誤消息 (Strange error message printed out for KeyError)

django 1.9 中的 from django.views.generic.simple import direct_to_template 相當於什麼 (What is the equivalent of from django.views.generic.simple import direct_to_template in django 1.9)

查詢嵌入列表中的數組 (Querying for array in embedded list)

如何在 Python 中搜索子字符串是否在二進製文件中? (How to search if a substring is into a binary file in Python?)

為什麼要避免 while 循環? (Why avoid while loops?)

使用python的json模塊解析json請求 (Parse a json request using json module of python)

為什麼使用 py2app 模塊創建 mac 文件時出現錯誤? (Why i am getting Error when creating mac file using py2app module?)

當 python 線程在網絡調用(HTTPS)中並且發生上下文切換時會發生什麼? (What happens when the python thread is in network call(HTTPS) and the context switch happens?)

如何繪製一條帶斜率和一個點的線?Python (How to plot a line with slope and one point given? Python)

Pickle 找不到我不使用的模塊? (Pickle can't find module that I am not using?)







留言討論