信创国产化替换如何推动企业自主创新与市场竞争力提升
779
2022-10-10
DataFrame(10):DataFrame运算——累计统计函数
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个元素的累乘积,和上面用法一致。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~