Reputation: 77
My input data as below
I want get output with rule:
My desire output as below:
Tks for all attentions & supports!
Upvotes: 1
Views: 97
Reputation: 640
Create a dictionary, mapping your desired day addition to different types and then map them to your column using list
and map
.
df['Date Received'] = pd.to_datetime(df['Date Received'])
change_dict = {
'Settlement': pd.Timedelta(days=2),
'Personal': pd.Timedelta(days=7),
'Cash': pd.Timedelta(days=1),
}
df['Date Checked'] = list(map(lambda x, y: x + change_dict[y], df['Date Recieved'], df['Type']))
If you are also worried about performance, this solution using list
, map
and dict mapping is more efficient than using .apply()
with if-else
.
Upvotes: 1
Reputation: 13582
Assuming that the dataframe is df
, first make sure that the Date Received
column is of datetime
df['Date Received'] = pd.to_datetime(df['Date Received'])
Assuming that there are only those three types (Settlement
, Personal
, Cash
), the following custom lambda function will do the work
df['Date Checked'] = df.apply(lambda x: x['Date Received'] + pd.Timedelta(days=2) if x['Type'] == 'Settlement' else x['Date Received'] + pd.Timedelta(days=7) if x['Type'] == 'Personal' else x['Date Received'] + pd.Timedelta(days=1), axis=1)
[Out]:
Date Received Type Date Checked
0 2022-09-09 Settlement 2022-09-11
1 2022-09-09 Personal 2022-09-16
2 2022-09-09 Cash 2022-09-10
Else, one might have to specify the Cash
as follows
df['Date Checked'] = df.apply(lambda x: x['Date Received'] + pd.Timedelta(days=2) if x['Type'] == 'Settlement' else x['Date Received'] + pd.Timedelta(days=7) if x['Type'] == 'Personal' else x['Date Received'] + pd.Timedelta(days=1) if x['Type'] == 'Cash' else x['Date Received'], axis=1)
[Out]:
Date Received Type Date Checked
0 2022-09-09 Settlement 2022-09-11
1 2022-09-09 Personal 2022-09-16
2 2022-09-09 Cash 2022-09-10
Upvotes: 1