又来求教 pandas 大拿了 - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
yaleyu
V2EX    Python

又来求教 pandas 大拿了

  •  
  •   yaleyu 2021-03-11 10:11:14 +08:00 3122 次点击
    这是一个创建于 1750 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如下一个表,想每当 C 列为 False 时候,D 列为 0,为 True 时候,D 列为 B 列的上一次 C 列为 False 到当前列的加总

    df = pd.DataFrame([['S1', 1, False], ['S1', 1, True], ['S2', 2, False], ['S2', 2, True], ['S2', 22, False], ['S2', 22, True], ['S3', 222, False], ['S3', 222, True]], columns=list('ABC')) print(df) A B C 0 S1 1 False 1 S1 1 True 2 S2 2 False 3 S2 2 True 4 S2 22 False 5 S2 22 True 6 S3 222 False 7 S3 222 True 

    用 for 循环切片每次的 False 到 True 再处理可以得到想要的结果,但是总觉得效率不高。

    用了下面的方法,得出来的结果不对,5 行 D 列应该是 44(22+22)而不是 48(2+2+22+22)

    df['D'] = np.where(df.C, df.groupby('A')['B'].cumsum(), 0) print(df) A B C D 0 S1 1 False 0 1 S1 1 True 2 2 S2 2 False 0 3 S2 2 True 4 4 S2 22 False 0 5 S2 22 True 48 6 S3 222 False 0 7 S3 222 True 444 
    12 条回复    2021-03-11 18:50:06 +08:00
    apake
        1
    apake  
       2021-03-11 11:33:22 +08:00
    为什么要 groubby('A'), 问题中没提到与 A 列有关
    shyrock
        2
    shyrock  
       2021-03-11 11:36:33 +08:00   1
    df['D'] = np.where(df.C, df.groupby('B')['B'].cumsum(), 0)
    print(df)
    cassidyhere
        3
    cassidyhere  
       2021-03-11 12:3355 +08:00
    如果 A/B 没规律的话,可以用自定义 window rolling
    from pandas.api.indexers import BaseIndexer
    window_size = df.C.groupby((df.C != df.C.shift(1)).cumsum()).agg('sum').max() # 最大连续次数
    class CustomIndexer(BaseIndexer):
    def get_window_bounds(self, num_values, min_periods, center, closed):
    start = np.empty(num_values, dtype=np.int64)
    end = np.empty(num_values, dtype=np.int64)
    for i in range(num_values):
    end[i] = i + 1
    j = i
    while j > 0 and self.use_expanding[j]:
    j -= 1
    start[i] = j
    return start, end
    indexer = CustomIndexer(window_size=window_size, use_expanding=df.C)
    res = df.B.rolling(indexer, min_periods=2).sum().fillna(0)
    yaleyu
        4
    yaleyu  
    OP
       2021-03-11 16:15:19 +08:00 via Android
    @apake 问题没描述得太清楚,应该是对每个 A 列的数据,当 C 列从 false 变化为 true 时候,加总 false 到 true 对应的行的 B 列
    yaleyu
        5
    yaleyu  
    OP
       2021-03-11 16:18:33 +08:00 via Android
    @shyrock 这个不行,B 列的值是不一样的,不能 groupby('B'),这里为了简化写成了 1, 1, 2, 2, 22, 22 等
    necomancer
        6
    necomancer  
       2021-03-11 16:58:23 +08:00
    df.D = df.groupby(df.C.eq(False).cumsum()).cumsum().D
    df.D[df.D <0]=0
    necomancer
        7
    necomancer  
       2021-03-11 17:03:40 +08:00
    df = pd.DataFrame([['S1', 1, False], ['S1', 1, True],
    ['S2', 2, False], ['S2', 2, True], ['S2', 22, False], ['S2', 22, True],
    ['S3', 222, False], ['S3', 222, True]],
    columns=list('ABC'))

    df['D'] = np.diff(np.where(df.C, df.groupby('A')['B'].cumsum(), 0), axis=0, prepend=0)

    df.D = df.groupby(df.C.eq(False).cumsum()).cumsum().D
    df.D[df.D <0]=0
    df
    A B C D
    0 S1 1 False 0
    1 S1 1 True 2
    2 S2 2 False 0
    3 S2 2 True 2
    4 S2 22 False 0
    5 S2 22 True 44
    6 S3 222 False 0
    7 S3 222 True 396
    necomancer
        8
    necomancer  
       2021-03-11 17:09:53 +08:00
    ……我是智障

    df['D'] = np.where(df.C, df.groupby(df.C.eq(False).cumsum()).B.cumsum(), 0)


    df


    A B C D
    0 S1 1 False 0
    1 S1 1 True 2
    2 S2 2 False 0
    3 S2 2 True 4
    4 S2 22 False 0
    5 S2 22 True 44
    6 S3 222 False 0
    7 S3 222 True 444
    milkpuff
        9
    milkpuff  
       2021-03-11 17:44:08 +08:00
    我选择 for 循环。。
    而且不要频繁对 pandas 切片和赋值,转成 numpy 操作速度提升一个数量级,最后结果再转到 pandas
    yaleyu
        10
    yaleyu  
    OP
       2021-03-11 18:05:09 +08:00
    @necomancer 这个牛逼,完全实现了需求,谢谢谢谢。
    yaleyu
        11
    yaleyu  
    OP
       2021-03-11 18:06:03 +08:00
    @cassidyhere 这个好深奥,不过完全实现了需求,万分感谢。
    yaleyu
        12
    yaleyu  
    OP
       2021-03-11 18:50:06 +08:00
    @necomancer @cassidyhere 哦,不对,把原始数据改一下更接近真实数据,好像就有点问题了,原贴编辑不了了,回复排版会乱,再开一贴求教大家吧
    t/760789
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     4032 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 33ms UTC 05:29 PVG 13:29 LAX 21:29 JFK 00:29
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86