循环索引和前一项

时间:2017-04-13 20:04:29

标签: python loops date pandas

我想循环查看日期列表,以获取日期和之前的日期之间的差异(例如4/13和3/13之间的差异)。

我正在寻找能够扫描几个日期的for循环

import pandas as pd
import numpy as np
raw_data = {'date' : pd.to_datetime(pd.Series(['2017-03-30','2017-03-31','2017-04-03','2017-04-04'])),
'age': [10,np.nan,50,30]}
df1 = pd.DataFrame(raw_data, columns = ['date','age'])

df1

输入数据

df2=df1.T


df2['new']=df2.iloc[:,3]-df2.iloc[:,2]

渴望的结果:

raw_data = {'date' : pd.to_datetime(pd.Series(['2017-03-30','2017-03-31','2017-04-03','2017-04-04'])),'age': [10,np.nan,50,30],
'diff': [10,-10,50,-20]}
output = pd.DataFrame(raw_data, columns = ['date','age','diff'])

output

1 个答案:

答案 0 :(得分:0)

如果您想知道日期之间的差异,则不需要循环。 也许你应该这样做:

df1['difference'] = (df1['date'] - df1['date'].shift(1)).apply(lambda x: pd.NaT if x is pd.NaT else x.days)

或者这个:

df1['difference'] = (df1['date'] - df1['date'].shift(-1)).apply(lambda x: pd.NaT if x is pd.NaT else x.days)