Created
September 8, 2021 16:38
-
-
Save sizhky/5a384534844a74b5a0022397cdf03338 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def add_datepart(df, fldname, drop=True, time=False): | |
"Helper function that adds columns relevant to a date." | |
fld = df[fldname] | |
fld_dtype = fld.dtype | |
if isinstance(fld_dtype, pd.core.dtypes.dtypes.DatetimeTZDtype): | |
fld_dtype = np.datetime64 | |
if not np.issubdtype(fld_dtype, np.datetime64): | |
df[fldname] = fld = pd.to_datetime(fld, infer_datetime_format=True) | |
targ_pre = re.sub('[Dd]ate$', '', fldname) | |
attr = ['Year', 'Month', 'Week', 'Day', 'Dayofweek', 'Dayofyear', | |
'Is_month_end', 'Is_month_start', 'Is_quarter_end', 'Is_quarter_start', 'Is_year_end', 'Is_year_start'] | |
if time: attr = attr + ['Hour', 'Minute', 'Second'] | |
for n in attr: df[targ_pre + n] = getattr(fld.dt, n.lower()) | |
df[targ_pre + 'Elapsed'] = fld.astype(np.int64) // 10 ** 9 | |
if drop: df.drop(fldname, axis=1, inplace=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment