3条回答 默认 最新
_Molala_ 2022-06-03 18:19关注使用DataFrame的apply函数就ok啦,我下面用几个小例子展示以下
import pandas as pd # 定义一个全局变量 s = 0 def f1(x): global s s = x['QTY'] + s # 每次使用全局变量来叠加返回 return s # 创建一个类似你的DataFrame d = [['Jan', 271], ['Feb', 109], ['Mar', 126], ['Apr', 123]] df = pd.DataFrame(d, columns=['Month', 'QTY']) print(df) print('---------------------') # 使用DataFrame自带的函数apply,具体去看一下官方文档吧~也很好理解 res = df.apply(f1, axis=1) # 生成是Series类型的数据 print(res, type(res)) print('---------------------') # 再将生成出来的Series加在原DataFrame上 df['Sub_sum'] = res print(df)最后结果输出为:
Month QTY 0 Jan 271 1 Feb 109 2 Mar 126 3 Apr 126 --------------------- 0 271 1 380 2 506 3 629 dtype: int64 <class 'pandas.core.series.Series'> --------------------- Month QTY Sub_sum 0 Jan 271 271 1 Feb 109 380 2 Mar 126 506 3 Apr 126 629评论 打赏 举报解决 1无用
