Skip to content

Instantly share code, notes, and snippets.

@justinhchae
Last active January 1, 2021 02:15
Show Gist options
  • Save justinhchae/ca70cfa5f0110af59392442fe56484be to your computer and use it in GitHub Desktop.
Save justinhchae/ca70cfa5f0110af59392442fe56484be to your computer and use it in GitHub Desktop.
Lambdas on Pandas DF with apply and one conditional
# replace col1 year with col2 year on a condition
# if does not meet condition, use the original col1 value
df[col_new] = df.apply(lambda x: x[col1].replace(year=x[col2].year)
if x[col1].year > curr_year else x[col1]
, axis=1)
# filter df where year is greater than current year
df = df[(df[col1].dt.year > curr_year)]
print(df[[col1, col_new, col2]].head(2))
# output
"""
event_date event_date_new received_date
2109-12-02 2019-12-02 2019-11-24
2109-12-02 2019-12-02 2019-11-24
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment