DataFrame(10):DataFrame运算——累计统计函数
程序员文章站
2024-03-25 21:23:22
...
1、相关函数说明
2、原始数据
df = pd.DataFrame({"id":["00{}".format(i) for i in range(1,10)],
"score":[2,3,4,4,5,6,7,7,8]})
display(df)
结果如下:
3、cumsum()函数:求前n个元素的累积值(很重要的一个函数)
df = pd.DataFrame({"id":["00{}".format(i) for i in range(1,10)],
"score":[2,3,4,4,5,6,7,7,8]})
display(df)
df["cumsum"] = df["score"].cumsum(axis=0)
display(df)
结果如下:
1)cumsum():分组求累计值
df = pd.DataFrame({"id":["001","001","002","003","001","002","002","003","003"],
"score":[2,3,4,4,5,6,7,7,8]})
display(df)
df["分组求累计值"] = df.groupby("id").cumsum()
df = df.sort_values(by=["id"])
display(df)
结果如下:
4、cummax()函数:求前n个元素中的最大值
df = pd.DataFrame({"score":[1,2,1,5,2,6,3,7,1]})
display(df)
df["前n个值中最大值"] = df["score"].cummax(axis=0)
display(df)
结果如下:
1)cummax()函数:分组求前n个元素中的最大值
df = pd.DataFrame({"id":["001","001","002","003","001","002","002","003","003"],
"date":["2020-01-01","2020-01-09","2020-01-05","2020-01-03",
"2020-01-08","2020-01-07","2020-01-02","2020-01-04","2020-01-06"],
"score":[1,2,1,5,2,6,3,7,1]})
display(df)
df = df.sort_values(by=["id","date"],ascending=[True,True])
df["前n个值中最大值"] = df.groupby("id")["score"].cummax()
display(df)
结果如下:
注意:cummin()函数的用法和cummax()函数的用法一致,可以自行下去尝试。
5、cumprod()函数:求前n个元素的累乘积
df = pd.DataFrame({"score":[1,2,1,5,2,6,3,7,1]})
display(df)
df["前n个值的累乘积"] = df["score"].cummax(axis=0)
display(df)
结果如下:
注意:对于分组求前n个元素的累乘积,和上面用法一致。
上一篇: ASP.NET网站开发--个性化用户配置