什么是通过更多索引范围(例如by 10:12和25:28)对数据帧进行切片的pythonic方法?我希望以更优雅的方式:
df = pd.DataFrame({'a':range(10,100)})
df.iloc[[i for i in range(10,12)] + [i for i in range(25,28)]]
Run Code Online (Sandbox Code Playgroud)
结果:
a
10 20
11 21
25 35
26 36
27 37
Run Code Online (Sandbox Code Playgroud)
像这样的东西会更优雅:
df.iloc[(10:12, 25:28)]
Run Code Online (Sandbox Code Playgroud)
谢谢!
我以为我理解了python中列表切片的基础知识,但是在切片上使用负步骤时收到了意外错误,如下所示:
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> a[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> a[:-1:-1]
[]
Run Code Online (Sandbox Code Playgroud)
(请注意,这是在Python 3.5中运行)
为什么[: - 1:-1]不会以与使用[:: - 1]的整个列表相同的方式反向遍历a [: - 1]切片?
我意识到你也可以使用list.reverse(),但试图更好地理解底层的python切片功能.
我试图通过取出子列表长度的复杂公式来进一步优化素数线程中的冠军解决方案.同一子序列的len()太慢,因为len很昂贵并且生成子序列很昂贵.这看起来稍微加快了功能,但我还是不能带走除法,尽管我只在条件语句中进行除法.当然,我可以尝试通过优化n的起始标记而不是n*n来简化长度计算...
我将division /整数除法//替换为与Python 3兼容
from __future__ import division
Run Code Online (Sandbox Code Playgroud)
如果这个递推公式可以帮助加速numpy解决方案,我会很有趣,但我没有经验使用numpy.
如果你为代码启用了psyco,那么故事会变得完全不同,而且Atkins筛选代码变得比这种特殊的切片技术更快.
import cProfile
def rwh_primes1(n):
# http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
""" Returns a list of primes < n """
sieve = [True] * (n//2)
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i//2]:
sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1)
return [2] + [2*i+1 for i in xrange(1,n/2) if sieve[i]]
def primes(n):
# http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
# recurrence formula for length by amount1 and amount2 Tony Veijalainen 2010
""" Returns a list of primes < n """
sieve = [True] * …Run Code Online (Sandbox Code Playgroud) 我有特定键的数组.我想获得前5个数组元素.我用array_splice().一切正常,但新阵列中的键是0,1,2,3,4.我想保留以前的数组键.我可以做到foreach,但我找到了优雅的方法.
我的代码:
$levels = array('a' => 1, 'b' =>2, 'c' => 3, 'd' => 4, 'f' => 5, 'g' => 6);
$levels = array_splice($levels, 5);
Run Code Online (Sandbox Code Playgroud)
先感谢您.对不起我的英语不好.
您将如何在以下代码中实现deleteRecords函数:
Example:
type Record struct {
id int
name string
}
type RecordList []*Record
func deleteRecords( l *RecordList, ids []int ) {
// Assume the RecordList can contain several 100 entries.
// and the number of the of the records to be removed is about 10.
// What is the fastest and cleanest ways to remove the records that match
// the id specified in the records list.
}
Run Code Online (Sandbox Code Playgroud) 我想为列表的一部分分配一个值.除了以下之一之外,还有更好的解决方案吗?
也许性能最好,但有些丑陋:
>>> l=[0,1,2,3,4,5]
>>> for i in range(2,len(l)): l[i] = None
>>> l
[0, 1, None, None, None, None]
Run Code Online (Sandbox Code Playgroud)
简洁(但我不知道Python是否认识到不需要重新排列列表元素):
>>> l=[0,1,2,3,4,5]
>>> l[2:] = [None]*(len(l)-2)
>>> l
[0, 1, None, None, None, None]
Run Code Online (Sandbox Code Playgroud)
同样的警告如上:
>>> l=[0,1,2,3,4,5]
>>> l[2:] = [None for _ in range(len(l)-2)]
>>> l
[0, 1, None, None, None, None]
Run Code Online (Sandbox Code Playgroud)
不确定是否使用库来执行这样一个简单的任务是明智的:
>>> import itertools
>>> l=[0,1,2,3,4,5]
>>> l[2:] = itertools.repeat(None,len(l)-2)
>>> l
[0, 1, None, None, None, None]
Run Code Online (Sandbox Code Playgroud)
我看到切片的赋值(对于for循环)的问题是Python可能会尝试准备"l"长度的变化.毕竟,通过插入更短/更长的切片来更改列表涉及复制列表AFAIK的所有元素(即所有引用).如果Python也在我的情况下这样做(虽然没有必要),操作变为O(n)而不是O(1)(假设我只是总是改变一些元素).
如果我实现这样的队列......
package main
import(
"fmt"
)
func PopFront(q *[]string) string {
r := (*q)[0]
*q = (*q)[1:len(*q)]
return r
}
func PushBack(q *[]string, a string) {
*q = append(*q, a)
}
func main() {
q := make([]string, 0)
PushBack(&q, "A")
fmt.Println(q)
PushBack(&q, "B")
fmt.Println(q)
PushBack(&q, "C")
fmt.Println(q)
PopFront(&q)
fmt.Println(q)
PopFront(&q)
fmt.Println(q)
}
Run Code Online (Sandbox Code Playgroud)
...我最终得到一个["A", "B", "C"]没有切片指向前两个元素的数组.由于切片的"开始"指针永远不会递减(AFAIK),因此永远不能访问这些元素.
Go的垃圾收集器是否足够智能以释放它们?
这个问题是关于访问数组和切片元素的速度,而不是关于将它们作为参数传递给函数的效率.
在大多数情况下,我希望数组比切片更快,因为切片是描述数组的连续部分的数据结构,因此在访问切片的元素时可能会涉及额外的步骤(间接地是其底层数组的元素) .
所以我写了一个小测试来测试一批简单的操作.有4个基准函数,前2个测试全局切片和全局数组,另外2个测试局部切片和本地数组:
var gs = make([]byte, 1000) // Global slice
var ga [1000]byte // Global array
func BenchmarkSliceGlobal(b *testing.B) {
for i := 0; i < b.N; i++ {
for j, v := range gs {
gs[j]++; gs[j] = gs[j] + v + 10; gs[j] += v
}
}
}
func BenchmarkArrayGlobal(b *testing.B) {
for i := 0; i < b.N; i++ {
for j, v …Run Code Online (Sandbox Code Playgroud) 在我的代码中,我经常需要从Python OrderedDict(来自collections包)获取一系列键+值的子集.切片不起作用(抛出TypeError: unhashable type),替代,迭代,很麻烦:
from collections import OrderedDict
o = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
# want to do:
# x = o[1:3]
# need to do:
x = OrderedDict()
for idx, key in enumerate(o):
if 1 <= idx < 3:
x[key] = o[key]
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来完成这项工作?
Numpy有一些非常有用的字符串操作,它们可以对通常的Python字符串操作进行矢量化.
与这些操作相比pandas.str,numpy strings模块似乎缺少一个非常重要的模块:能够切割数组中的每个字符串.例如,
a = numpy.array(['hello', 'how', 'are', 'you'])
numpy.char.sliceStr(a, slice(1, 3))
>>> numpy.array(['el', 'ow', 're' 'ou'])
Run Code Online (Sandbox Code Playgroud)
我是否错过了具有此功能的模块中的一些明显方法?否则,有一种快速的矢量化方式来实现这一目标吗?
slice ×10
python ×5
arrays ×4
go ×3
benchmarking ×1
indexing ×1
list ×1
numpy ×1
pandas ×1
performance ×1
php ×1
primes ×1
python-2.7 ×1
reverse ×1
string ×1