我有2个DataFrames
df1由列组成:person_id,day,flag
df2由列组成:person_id,day_start,day_end
我想添加到df2列num_flags
,它会在flag
和person_id
区间内显示day_start < day < day_end
列的总和。
没有复杂的循环,这是最快的方法吗?我正在寻求像merge
答案 0 :(得分:1)
>>> df = pd.merge(df1,df2, on="person_id", how="outer")
>>> df["lies_between"] = df.day.between(df.day_start, df.day_end,inclusive=False)
>>> x = pd.pivot_table(df,values="flags",columns="lies_between", index="person_id",aggfunc=np.sum)
>>> x.reset_index(drop=False,inplace=True)
>>> x[["person_id", True]]
这可能会有所帮助:
>>> help(pandas.Series.between_time)