python - Pandas calculate days elapsed and percent change -
i have df hierarchical index (id & date) , measure m. add 2 new measures df; first percent change of measure m prior observation , second days elapsed. within "window" of id (i.e. first observation within each id 0 both new measures)
one way group id, differences want , sew new dataframe. suggestions on how better and/or in place welcome.
new_df = pd.dataframe() grouped = your_df.groupby('id') grp_id in grouped.groups: grp = grouped.get_group(grp_id) grp["diff"] = np.concatenate([np.array([0]),np.diff(grp['m'].values)]) # differences of m grp["days_elapsed"] = np.concatenate([np.array([none]),days_elapsed(grp.index.values)]) # new_df = new_df.append(grp)
and function elapsed days pandas timeindex:
def days_elapsed(l): res= [] print l x in range(1,len(l)): res.append((l[x]-l[x-1])/np.timedelta64(1, 'd')) return res
Comments
Post a Comment