【问题标题】:How to replace value in sequences of a boolean list?如何替换布尔列表序列中的值?
【发布时间】:2020-08-24 00:40:08
【问题描述】:

我有一个这样的列表:

list_1 = [True, False, True, False, True, True, True, False, False, False, True, True, False]

在此列表中,有以False 开头并以True 结尾的序列。我需要帮助以这种方式实现此列表的替换值:

  • 将这些序列的False 值替换为-2^k 系列。每个序列的最后一个False 之后的True 值为+2^kk 为该值在序列中的位置。
  • 不属于任何这些序列的其他True 值将保留值1

输出如下所示:

list_2 = [1, -1, 2, -1, 2, 1, 1, -1, -2, -4, 8, 1, -1]

【问题讨论】:

    标签: python arrays pandas list numpy


    【解决方案1】:

    既然你标记了pandas

    # turn data into series
    s = pd.Series(list_1)
    
    # mark the blocks ending with True
    blocks = s.shift(fill_value=0).cumsum()
    
    # compute the positions within blocks and raise to power 2
    powers = 2**s.groupby(blocks).cumcount()
    
    #output:
    np.where(s, 1,-1)*powers.values
    

    输出:

    array([ 1, -1,  2, -1,  2,  1,  1, -1, -2, -4,  8,  1, -1])
    

    【讨论】:

    • 工作得很好。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-06-21
    • 2011-12-22
    • 1970-01-01
    • 2016-05-18
    • 2015-01-21
    • 2022-11-10
    • 2022-08-16
    • 1970-01-01
    相关资源
    最近更新 更多