繁体   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