【问题标题】:Efficient assignment into a pandas Series based on a bool Series基于布尔系列的熊猫系列的有效分配
【发布时间】:2017-08-12 03:16:40
【问题描述】:

给定一个 Series 的布尔值,我想创建一个新的 Series,它从 0 开始,并递增布尔值 Series 中的每个对应条目为 True。这是一个例子:

s = pd.Series([False, True , False, False, False, True, False, False, True, False])

看起来像:

0    False
1     True
2    False
3    False
4    False
5     True
6    False
7    False
8     True
9     False

我正在寻找一种高效且尽可能优雅的操作,无需循环,以获得以下Series

0    0
1    1
2    1
3    1
4    1
5    2
6    2
7    2
8    3
9    3

【问题讨论】:

    标签: python python-3.x pandas boolean series


    【解决方案1】:

    使用pd.Series.cumsum

    s.cumsum()
    
    0    0
    1    1
    2    1
    3    1
    4    1
    5    2
    6    2
    7    2
    8    3
    9    3
    dtype: int64
    

    【讨论】:

    • 很好,我知道这个函数,但认为它只对一系列 dtypes int 或 float 起作用。
    • @splinter boolint 的子类。 issubclass(bool, int) 计算结果为 True
    猜你喜欢
    • 1970-01-01
    • 2022-06-27
    • 2019-01-14
    • 2016-01-15
    • 1970-01-01
    • 2021-12-28
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多