0

I have a dataframe with columns like this. The final df should contain a new column after taking the First_Date column and subtracting the corresponding unit and the corresponding value df = pd.DataFrame({"First_Date":[pd.to_datetime("2020-01-01")]*5, "Unit":['Years','Months','Days','Years','Days'], "Value":[1,2,2,3,5]})

The output column should have the values: 2019-01-01 2019-11-01 2020-12-29 2017-01-01 2020-12-27

I have tried the timedelta module but the inputs to that is not accepting values from a different column. For example, it does not take

df.apply(lambda x: x['First_Date']- timedelta(x['Unit'] = x['Value'])

1 Answer 1

1

Named arguments cannot be supplied from a variable as far as I am aware.

You could, however, create a one-hot encoding for your Unit-column and scale it by the Value-column to create a description of your delta:

df_augmented = df.merge(pd.get_dummies(df.Unit).mul(df.Value, axis=0),
                        left_index=True, right_index=True)

  First_Date    Unit  Value  Days  Months  Years
0 2020-01-01   Years      1     0       0      1
1 2020-01-01  Months      2     0       2      0
2 2020-01-01    Days      2     2       0      0
3 2020-01-01   Years      3     0       0      3
4 2020-01-01    Days      5     5       0      0

Now, you can statically supply all values to the function (as in years=df_augmented.Years, months=df_augmented.Months etc) and all should be well.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.