【问题标题】:Converting a list of instants to a list of increments [duplicate]将瞬间列表转换为增量列表[重复]
【发布时间】:2020-04-13 20:42:26
【问题描述】:

我需要将瞬间列表a 转换为增量列表da,例如从列表中

a=[1.,3.,4.,8.]

我想要清单

da=[2.,1.,4.]

“手动”操作非常简单:

da=[]
for i in range(len(a)-1):
    da.append(a[i+1]-a[i])

在没有for 循环的情况下,python 是否提供了一种更综合、更优雅的方法?

a 的解决方案是一个 numpy 数组而不是一个列表也可以。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    Numpy 有一个 diff() 函数可以做到这一点:

    import numpy as np
    
    a = np.array([1.,3.,4.,8.])
    
    np.diff(a)
    # array([2., 1., 4.])
    

    【讨论】:

      【解决方案2】:

      既然你有 numpy 标签:

      import numpy as np
      
      a=np.array([1., 3., 4., 8.])
      
      da = a[1:] - a[:-1]
      da
      array([2., 1., 4.])
      

      虽然可以认为np.diff 更快,但实际上速度稍慢,检查性能:

      import timeit
      import pandas as pd
      
      def timeit_diff(s):
          a = np.random.rand(s)
      
          t0 = timeit.default_timer()
          np.diff(a)
          return timeit.default_timer() - t0
      
      def timeit_shift(s):
          a = np.random.rand(s)
          t0 = timeit.default_timer()
          a[1:] - a[:-1]
          return timeit.default_timer() - t0
      
      sizes = [10**i for i in range(10)]
      
      times = [[s, timeit_diff(s), timeit_shift(s)] for s in sizes]
      
      df = pd.DataFrame(times, columns=['size', 'diff_method', 'difference'])
      
      df.set_index('size', inplace=True)
      df
                  diff_method  difference
      size                               
      1              0.000031    0.000004
      10             0.000011    0.000002
      100            0.000009    0.000010
      1000           0.000027    0.000004
      10000          0.000020    0.000013
      100000         0.000827    0.001420
      1000000        0.007460    0.009606
      10000000       0.061235    0.061254
      100000000      0.641381    0.597128
      1000000000    23.763331   18.087844
      
      df.plot(figsize=(12,8))
      

      【讨论】:

        猜你喜欢
        • 2019-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-29
        • 1970-01-01
        • 2021-06-09
        • 2021-09-08
        • 2019-11-27
        相关资源
        最近更新 更多