Mr.Bean
Mr.Bean

Reputation: 77

How to return next day with str condition in Pandas?

My input data as below

enter image description here

I want get output with rule:

  1. If column "Type" == "Settlement" return Date Recieved + 2
  2. If column "Type" == "Personal" return Date Recieved + 7
  3. If column "Type" == "Cash" return Date Recieved + 1

My desire output as below:

enter image description here

Tks for all attentions & supports!

Upvotes: 1

Views: 97

Answers (2)

Onur Guven
Onur Guven

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.

runtime benchmark

Upvotes: 1

Gonçalo Peres
Gonçalo Peres

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

Related Questions