1 回答
TA贡献1995条经验 获得超2个赞
这里非常复杂的部分是填写日期。我使用了申请,但我不确定这是最好的方法
import pandas as pd
data = [{"game_id":"Racing","user_id":"ABC123","amt":5,"date":"2020-01-01"},
{"game_id":"Racing","user_id":"ABC123","amt":1,"date":"2020-01-04"},
{"game_id":"Racing","user_id":"CDE123","amt":1,"date":"2020-01-04"},
{"game_id":"DH","user_id":"CDE123","amt":100,"date":"2020-01-03"},
{"game_id":"DH","user_id":"CDE456","amt":10,"date":"2020-01-02"},
{"game_id":"DH","user_id":"CDE789","amt":5,"date":"2020-01-02"},
{"game_id":"DH","user_id":"CDE456","amt":1,"date":"2020-01-03"},
{"game_id":"DH","user_id":"CDE456","amt":1,"date":"2020-01-03"}]
df = pd.DataFrame(data)
# we want datetime not object
df["date"] = df["date"].astype("M8[us]")
# we will need to merge this at the end
grp = df.groupby("game_id")['user_id']\
.nunique()\
.reset_index(name="Total_unique_payers_per_game")
# sum amt per game_id date
df = df.groupby(["game_id", "date"])["amt"].sum().reset_index()
# dates from 2020-01-01 till the max date in df
dates = pd.DataFrame({"date": pd.date_range("2020-01-01", df["date"].max())})
# add missing dates
def expand_dates(x):
x = pd.merge(dates, x.drop("game_id", axis=1), how="left")
x["amt"] = x["amt"].fillna(0)
return x
df = df.groupby("game_id")\
.apply(expand_dates)\
.reset_index().drop("level_1", axis=1)
df["Cum_rev"] = df.groupby("game_id")['amt'].transform("cumsum")
# this is equivalent as long as data is sorted
# df["Cum_rev"] = df.groupby("game_id")['amt'].cumsum()
# merge unique payers per game
df = pd.merge(df, grp, how="left")
# dates difference
df["Age"] = "2020-01-01"
df["Age"] = df["Age"].astype("M8[us]")
df["Age"] = (df["date"]-df["Age"]).dt.days
# then you can eventually filter
df = df[["game_id", "Age",
"Cum_rev", "Total_unique_payers_per_game"]]\
.rename(columns={"game_id":"Game"})
添加回答
举报