Q:

How to add a new column to a pandas dataframe while calculate the elements?

I want to add a new column to a pandas df which will be calculated based on another column. 
Here's a shourtcut of the df:

If the date is between start_date1 and end_date1 it should output in the period column "0". If the date is between start_date2 and end_date2 output a "1" and so on.
Is there any way to do this without a loop?
Thanks for your help :)
Larry

A:

First of all you need to check if your column date has a datetime format.
You can check this with df.dtypes. If it does not have the format date (datetime64), you have to convert it to datetime with:
df['date'] = pd.to_datetime(df.date, format='%Y%m%d', errors='ignore')

Please note that the argument errors='ignore' has its risks, so its optional.
Now to make your calculated field, you can do this:
# define function to calculate periods based on date
def calculate_period(row): 
    if row['date'] > start_date1 & row['date'] < end_date1:
        return "0"

    elif row['date'] > start_date2 & row['date'] < end_date2:
        return "1"

    elif row['date'] > start_date3 & row['date'] < end_date3:
        return "2"

    else:
        return "unknown"

# apply function to create the new column
df['period'] = df.apply(calculate_period, axis=1)

If you need more period values, you can extend the elif statements as you like.
Since there is lack of information about your data. I assumed that start_date1 and end_date1 are variables you defined.
If these are columns as well. The function would look like this:
# define function to calculate periods based on date
def calculate_period(row): 
    if row['date'] > row['start_date1'] & row['date'] < row['end_date1']:
        return "0"

    elif row['date'] > row['start_date2'] & row['date'] < row['end_date2']:
        return "1"

    elif row['date'] > row['start_date3'] & row['date'] < row['end_date3']:
        return "2"

    else:
        return "unknown"

# apply function to create the new column
df['period'] = df.apply(calculate_period, axis=1)

Good luck.

