【问题标题】:Change the sign of the number in the pandas series更改熊猫系列中数字的符号
【发布时间】:2019-01-10 08:08:18
【问题描述】:

如果我有,如何更改系列中的符号:

1、2、3、4、5、6、7、8、9、10、11、12、13

并且需要得到:

1、2、3、-4、-5、-6、8、9、10、-11、-12、-13

我需要能够设置周期(现在等于 3)和函数开始的索引(现在等于 3)。

例如,如果我指定 2 作为索引,我得到

1、2、-3、-4、-5、6、8、9、-10、-11、-12、13

我需要将此函数顺序应用到每一列,因为应用到整个 DataFrame 会导致内存错误。

【问题讨论】:

    标签: python pandas time-series series


    【解决方案1】:

    使用 numpy.where 整数除以 (//) 和模 (%) 作为布尔掩码:

    s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
    
    N = 3
    #if default RangeIndex
    m = (s.index // N) % 2 == 1
    #general index
    #m = (np.arange(len(s.index)) // N) % 2 == 1
    s = pd.Series(np.where(m, -s, s))
    print (s)
    0      1
    1      2
    2      3
    3     -4
    4     -5
    5     -6
    6      7
    7      8
    8      9
    9    -10
    10   -11
    11   -12
    12    13
    dtype: int64
    

    编辑:

    N = 3
    M = 1
    m = np.concatenate([np.repeat(False, M), 
                       (np.arange(len(s.index) - M) // N) % 2 == 0])
    
    s = pd.Series(np.where(m, -s, s))
    print (s)
    0      1
    1     -2
    2     -3
    3     -4
    4      5
    5      6
    6      7
    7     -8
    8     -9
    9    -10
    10    11
    11    12
    12    13
    dtype: int64
    

    【讨论】:

    • 谢谢,你的代码很好。我希望能够设置函数开始的索引,以及按顺序将其应用于每一列的能力。
    • @hyper - 抱歉,不明白。如果s = pd.Series([8,9,1]) 则需要将索引[0,1,2] 更改为以M = 5 之类的数字开始索引[5,6,7] 吗?还是别的什么?
    • 如果s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])N=3 并且我想从系列的第五个成员中更改符号,那么我将得到1, 2, 3, 4, 5, -6, -7, -8, 9, 10, 11, -12, -13, -14
    • @hyper - 所以M=5?总是 M > N,这里是5>3 ?
    • 否,M = 1 和 N=3 1, -2, -3, -4, 5, 6, 7, -8, -9, -10, 11, 12, 13, -14
    猜你喜欢
    • 2019-11-23
    • 2014-04-09
    • 2022-11-18
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2021-01-11
    相关资源
    最近更新 更多