Etienne
Etienne

Reputation: 108

How to replace dates in a column in a pandas dataframe?

I want to fill a column with particular dates. First, I create a column of dates filled only with the date of today. Then, I compute the date I want to replace for each location. The index is in the following format: '%Y-%m-%d'

The computation works well. It is the last line which does not work

There is my code:

for j in range(1, 154):
    result['LTD_' + str(j)] = dt.date(dt.datetime.now().year,dt.datetime.now().month,dt.datetime.now().day) #creating a column of dates filled with today day
    for i in range(0, len(result.index)):
        date_selected = result.iloc[[i]].index
        date_month = add_months(date_selected,j)
        delivery_month = date_month.month
        delivery_year = date_month.year
        delivery = dt.date(delivery_year, delivery_month, result[(result.index.month == (delivery_month)) & (result.index.year == delivery_year)].index.day.min())
        delloc = result.index.get_loc(str(delivery))
        ltdloc = delloc - 3
        result.iloc[[i]]['LTD_' + str(j)] = dt.date(result.iloc[[ltdloc]].index.year, result.iloc[[ltdloc]].index.month, result.iloc[[ltdloc]].index.day)

The last line does not work to replace the today date by the computed date. Nothing happened. date.replace generates an error.

Upvotes: 1

Views: 1293

Answers (1)

jezrael
jezrael

Reputation: 862406

Now is ix deprecated, so need loc with selecting index by position:

result.loc[result.index[i], 'LTD_' + str(j)] = ...

Or iloc with get_loc for position of column name:

result.iloc[i, result.columns.get_loc('LTD_' + str(j))] = ...

Another solution is:

result['LTD_' + str(j)].iloc[[i]] = ...

Upvotes: 1

Related Questions