如何替换熊猫数据框中列的日期?
问题描述:
我想用特定日期填写一列。首先,我创建一个仅填充今天日期的日期列。然后,我计算我想要替换每个位置的日期。该索引采用以下格式:'%Y-%m-%d'
如何替换熊猫数据框中列的日期?
计算效果良好。它是不起作用
还有就是我的最后一行代码:
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)
最后一行不起作用通过计算日期,以取代今天的日期。什么都没发生。 date.replace生成一个错误。
答
现在是ix
deprecated,所以需要loc
与位置选择指数:
result.loc[result.index[i], 'LTD_' + str(j)] = ...
result.iloc[i, result.columns.get_loc('LTD_' + str(j))] = ...
另一种解决方案是:
result['LTD_' + str(j)].iloc[[i]] = ...
什么是错误?如果使用最后一行'result.iloc [[i]] ['LTD_'+ str(j)] = 0',那么失败了?如果使用'print(dt.date(result.iloc [[ltdloc]] .index.year,result.iloc [[ltdloc]] .index.month,result.iloc [[ltdloc]] .index.day))'它失败了? – jezrael
'result.iloc [[i]] ['LTD_'+ str(j)] = 0',什么也没有发生。我还有今天的日期('2017-05-25')。但是,'print(dt.date(result.iloc [[ltdloc]] .index.year,result.iloc [[ltdloc]] .index.month,result.iloc [[ltdloc]] .index.day))'在'result.iloc [[i]] ['LTD_'+ str(j)]''中替换''%Y-%m-%d''格式的好日期。 –
嗯,没有数据,它确实很难,但'result ['LTD_'+ str(j)]。iloc [i]'或'result ['LTD_'+ str(j)]。iloc [[i]]'应该有效。 – jezrael