gpt4 book ai didi

python - 将日期函数应用于列以提取日期属性

转载 作者:行者123 更新时间:2023-12-01 01:49:17 26 4
gpt4 key购买 nike

我正在尝试用 python 构建一个客户函数,该函数可以处理各种与日期相关的任务,以便我可以在各种情况下轻松使用。

我似乎在努力思考如何将其应用到整个专栏。

import pandas as pd
import datetime

df = pd.DataFrame({'dates' : ['2018-01-02','2018-06-15','2018-07-07']})


def get_date_attribute(date_attribute,date_field):

"""
Take in a date in YYYY-MM-DD format and return the month
"""

mydate = datetime.datetime.strptime(date_field, "%Y-%m-%d")
if date_attribute =='month':
result = mydate.month()
elif date_attribute =='year':
result = mydate.year()
elif date_attribute=='day':
result = mydate.day()
else:
print("Valid values: 'month','day','year'")

return(result)


df['month']= df.apply(get_date_attribute(date_attribute='month',date_field='dates'))

最佳答案

您可以对其进行矢量化。定义一个函数

  1. 将字段列转换为日期时间,并且
  2. 使用 getattr 动态提取感兴趣的属性

现在,通过 DataFrame.pipe 应用此函数。

def get_date_attr(df, attr, field):
return getattr(
pd.to_datetime(df[field], errors='coerce').dt, attr)

df.pipe(get_date_attr, attr='month', field='dates')

0 1
1 6
2 7
Name: dates, dtype: int64

df.pipe(get_date_attr, attr='day', field='dates')

0 2
1 15
2 7
Name: dates, dtype: int64

关于python - 将日期函数应用于列以提取日期属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50900002/

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