我正在尝试在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'))
最佳答案
您可以矢量化它。定义一个函数
将字段列转换为日期时间,并
使用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/