簡體   English   中英

加快應用 function 在 pandas (python)

[英]Speed up the apply function in pandas (python)

我正在使用包含字符串格式日期的 Dataframe。 日期看起來像這樣:19620201 所以首先是年,然后是月,然后是日。

我想將這些日期轉換為日期時間。 我試着用這個: pd.to_datetime(df.Date)

但它不起作用,因為某些日期的日期為“00”,有時是月份,有時甚至是年份。

我不想放棄這些日期,因為我仍然需要年份或月份。

所以我試着寫一個像這樣的 function :

def handle_the_00_case(date):
    try:
        if date.endswith("0000"):
            return pd.to_datetime(date[:-4], format="%Y")
        elif date.endswith("00"):
            return pd.to_datetime(date[:-2], format="%Y%m")

        return pd.to_datetime(date, format="%Y%m%d")
    except ValueError:
        return

並使用以下語句: df.Date.apply(handle_the_00_case)

但這確實太長而無法計算。

您對我如何提高速度有什么想法嗎? 我嘗試了np.vectorize()和 swifter 庫,但這不起作用,我知道我應該改變編寫 function 的方式,但我不知道如何。

如果你能幫助我,謝謝::)

第一個想法是使用矢量化解決方案,將列傳遞到to_datetime並通過numpy.where生成輸出列:

d1 = pd.to_datetime(df['Date'].str[:-4], format="%Y", errors='coerce')
d2 = pd.to_datetime(df['Date'].str[:-2], format="%Y%m", errors='coerce')
d3 = pd.to_datetime(df['Date'], format="%Y%m%d", errors='coerce')

m1 = df['Date'].str.endswith("0000")
m2 = df['Date'].str.endswith("00")

df['Date_out'] = np.where(m1, d1, np.where(m2, d2, d3)) 

您應該首先將該列轉換為有效日期,然后只轉換一次日期時間:

date = df['Date'].str.replace('0000$','0101')
date = date.str.replace('00$','01')
date = pd.to_datetime(date, format="%Y%m%d")

暫無
暫無

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

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