I have this dataframe made on the polars library of python :
from datetime import date
import polars as pl
my_df = pl.DataFrame({
'Col1': [1, 1, 1, 1, 2, 2, 3, 3],
'Col2': [date(2020, 1, 31), date(2020, 1, 31), date(2020, 1, 31),
date(2020, 1, 31), date(2020, 1, 31), date(2020, 1, 31),
date(2020, 1, 31), date(2020, 1, 31)],
})
I want the date in field 'col2' to change month every time the value in field 'col1' changes.
Could you please help me?
Thank you in advance for your answers.
Note that month=2 and 3 doesn't contain 31 days. Here's working script -
import polars as pl
import numpy as np
from datetime import date
df = pl.DataFrame({
'Col1': [1, 1, 1, 1, 2, 2, 3, 3],
'Col2': [date(2020, 1, 25), date(2020, 1, 25), date(2020, 1, 25),
date(2020, 1, 25), date(2020, 1, 25), date(2020, 1, 25),
date(2020, 1, 25), date(2020, 1, 25)],
})
df = df.with_columns(pl.Series('Col2_updated', list(map(lambda col1, col2: col2.replace(month=col1), df['Col1'], df['Col2']))))
print(df)
Output -