gpt4 book ai didi

python - 提高 pandas 中日期时间操作的性能

转载 作者:行者123 更新时间:2023-12-01 02:45:22 25 4
gpt4 key购买 nike

我有一个大数据集,需要进行日期操作,并且由于花费的时间太长,我想知道是否有其他方法可以提高速度。数据框如下所示:

Date, Month
2017-01-01, 0
2017-01-01, 1
2017-01-01, 2

我需要创建另一个列,将月份列添加到日期列,因此它看起来如下所示:

Date, Month, newDate
2017-01-01, 0, 2017-01-01
2017-01-01, 1, 2017-02-01
2017-01-01, 2, 2017-03-01

我当前的方法是使用 apply 函数和relativedelta 方法,例如:

def newDateCalc(self, row):
return row[0] + relativedelta(months = row[1])

df['newDate'] = df[['日期', '月份']].apply(lambda row: newDateCalc(row), axis = 1)

感谢您提前提供的帮助,

最佳答案

这是我的矢量化尝试:

df['newDate'] = (df.Date.values.astype('M8[M]') + 
df.Month.values * np.timedelta64(1, 'M')).astype('M8[D]')

结果:

In [106]: df
Out[106]:
Date Month newDate
0 2017-01-01 0 2017-01-01
1 2017-01-01 1 2017-02-01
2 2017-01-01 2 2017-03-01

关于python - 提高 pandas 中日期时间操作的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45313374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com