请指导我。我有以下数据框:
df
dob date
1 8/11/1966 3/1/1990, 5/1/2000, 8/1/2010
2 6/13/1970 4/1/2014, 3/1/2016, 4/1/2017
3 10/10/2010 4/13/2017
我的目标是生成一个列,显示' dob'之间的年份差异。和' date'像这样的列:
df
dob date difference
1 8/11/1966 3/1/1990, 5/1/2000, 8/1/2010 23.570, 23.740, 23.992
2 6/13/1970 4/1/2014, 3/1/2016, 4/1/2017 43.833, 45.751, 46.836
3 10/10/2010 4/13/2017 6.512
使用以下代码,
diff = (df['date'].sub(df['dob']))/365
diff = (diff / np.timedelta64(1, 'D')).astype(float)
df['difference'] = diff.round(3)
我能够计算单个日期存在时的差异,但是当一个单元格中有多个值用逗号分隔时,它不起作用。我怎样才能实现目标?先感谢您。
答案 0 :(得分:3)
考虑数据框df
df = pd.DataFrame(dict(
dob=['8/11/1996', '6/13/1970'],
date=[['3/1/1990', '5/1/2000', '8/1/2010'],
['4/1/2014', '3/1/2016', '4/1/2017']]
)).reindex_axis(['dob', 'date'], 1)
l = df.date.str.len()
ilvl0 = df.index.repeat(l)
ilvl1 = np.concatenate(l.apply(np.arange))
date = pd.Series(
pd.to_datetime(np.concatenate(df.date.values)),
[ilvl0, ilvl1]
)
difference = date.sub(
dob, level=0).dt.days.div(365.25).groupby(level=0).apply(list)
df.assign(difference=difference)
dob date difference
0 8/11/1996 [3/1/1990, 5/1/2000, 8/1/2010] [-6.45, 3.72, 13.97]
1 6/13/1970 [4/1/2014, 3/1/2016, 4/1/2017] [43.8, 45.72, 46.8]
OLD ANSWER
date_df = pd.to_datetime(
pd.DataFrame(df.date.values.tolist(), df.index).stack()
).unstack()
有点神奇......
df.assign(
difference=date_df.sub(
pd.to_datetime(df.dob), 0
).stack().dt.days.groupby(level=0).apply(list)
)
dob date difference
0 1996-08-11 [3/1/1990, 5/1/2000, 8/1/2010] [-2355, 1359, 5103]
1 1970-06-13 [4/1/2014, 3/1/2016, 4/1/2017] [15998, 16698, 17094]
如果你想要它多年而不是几天
df.assign(
difference=date_df.sub(
pd.to_datetime(df.dob), 0
).stack().apply(lambda x: x.days / 365.25).round(2).groupby(level=0).apply(list)
)
dob date difference
0 8/11/1996 [3/1/1990, 5/1/2000, 8/1/2010] [-6.45, 3.72, 13.97]
1 6/13/1970 [4/1/2014, 3/1/2016, 4/1/2017] [43.8, 45.72, 46.8]