如何有效地将pandas.Timestamp函数应用于完整的数据帧/列?

2024-05-19 01:13:52 发布

您现在位置:Python中文网/ 问答频道 /正文

Pandas是许多数据任务的绝佳工具。许多函数都经过了优化,可以有效地应用于列,而不是单个单元格/行。一个这样的函数是to_datetime()函数,我将在本问题后面的部分中使用它作为示例。然而,pandas中有许多命令,我从文档中可以看出,它们与数据帧没有直接关系。我感兴趣的特定函数是^{}函数,但是pandas.Timestamp类中有许多函数(可能还有其他pandas类)符合此描述且具有最少文档的有没有办法将这些函数高效地广播到一整列的数据中?如果有,我该怎么做

注意:我知道我可以使用apply()函数,但这显然比我想象的慢(在我的测试中大约5倍)。apply()函数也不限于pandas函数,所以我觉得一定有办法做到这一点(否则,pandas.Timestamp类为什么要在datetime对单个值做同样的事情时呢?)。请参阅下面的代码以获取示例,在该示例中,我将pandas.to_datetime()函数与datetime.strptime()函数应用于每一行进行比较

import pandas as pd
import datetime
from faker import Faker
import time
import copy

# Setting up fake dataframe:
Faker.seed(0)
fake = Faker()

observations=1000

dates=[fake.date_between(start_date=datetime.datetime(2020,1,1),end_date=datetime.datetime(2020,1,31)) for _ in range(observations)]
index=[x for x in range(observations)]

df=pd.DataFrame({'id' : index,'dates' : dates},columns=['id','dates'])

# Converting datetime object to string:
df['dates']=df['dates'].apply(lambda x: x.strftime('%Y-%m-%d'))

# Copy dataframe to run two time tests:
df2=copy.copy(df)

# Speed of the apply() function:
tic = time.perf_counter()
df['dates']=df['dates'].apply(lambda x: datetime.datetime.strptime(x,'%Y-%m-%d'))
toc = time.perf_counter()
print(f'pandas apply(lambda) completed in {toc-tic:0.4f} seconds')

# speed of the to_datetime() function:
tic = time.perf_counter()
df2['dates']=pd.to_datetime(df2['dates'],format='%Y-%m-%d')
toc = time.perf_counter()
print(f'pandas to_datetime() completed in {toc-tic:0.4f} seconds')

#Script returns:
#pandas apply(lambda) completed in 0.0107 seconds
#pandas to_datetime() completed in 0.0021 seconds

Tags: tolambda函数inimportpandasdfdatetime
1条回答
网友
1楼 · 发布于 2024-05-19 01:13:52

获得datetime64[ns]数据类型后,可以访问大部分时间函数(一旦有了datetimeindex,就会创建该类型:例如使用date_rangeto_datetime

然后可以使用dt accessor高效地强制转换所有类似datetime的函数:

df['dates'].dt.isocalendar()

相关问题 更多 >

    热门问题