用 pandas 和 numpy Python 替换列表理解
Replacing list comprehensions with pandas and numpy Python
下面的函数使用切片一次获取2个索引之间的最大值。所以它得到 0 and 10
和 10 and 12
之间的最大值等等。函数是从这个post的答案中推导出来的。有没有一种方法可以像 pd.Series()
这样的 pandas 函数形式替换列表推导式。或者如果可能的话,把它作为一个 numpy 函数来做。
list_ = np.array([9887.89, 9902.99, 9902.99, 9910.23, 9920.79, 9911.34, 9920.01, 9927.51, 9932.3, 9932.33, 9928.87, 9929.22, 9929.22, 9935.24, 9935.24, 9935.26, 9935.26, 9935.68, 9935.68, 9940.5])
indexes = np.array([0,10,12,14])
chunks = np.split(list_, indexes[1:-1])
MAX=([c.max() for c in chunks])
我会推荐这个:
MAX = np.maximum.reduceat(list_,indexes[:-1])
输出:
array([9932.33, 9929.22, 9940.5 ])
另一种不会提高你的表现而只是在你的答案中替代列表理解的方法(事实上,甚至可能稍微慢一点):
max = np.vectorize(np.max)
MAX = max(chunks)
下面的函数使用切片一次获取2个索引之间的最大值。所以它得到 0 and 10
和 10 and 12
之间的最大值等等。函数是从这个postpd.Series()
这样的 pandas 函数形式替换列表推导式。或者如果可能的话,把它作为一个 numpy 函数来做。
list_ = np.array([9887.89, 9902.99, 9902.99, 9910.23, 9920.79, 9911.34, 9920.01, 9927.51, 9932.3, 9932.33, 9928.87, 9929.22, 9929.22, 9935.24, 9935.24, 9935.26, 9935.26, 9935.68, 9935.68, 9940.5])
indexes = np.array([0,10,12,14])
chunks = np.split(list_, indexes[1:-1])
MAX=([c.max() for c in chunks])
我会推荐这个:
MAX = np.maximum.reduceat(list_,indexes[:-1])
输出:
array([9932.33, 9929.22, 9940.5 ])
另一种不会提高你的表现而只是在你的答案中替代列表理解的方法(事实上,甚至可能稍微慢一点):
max = np.vectorize(np.max)
MAX = max(chunks)