您面临的问题可能与查看与复制语义有关。
df.ix[1:N] # uses slicing => operates on a view
df.ix[np.arange(1,N)] # uses fancy indexing => "probably" creates a copy first
我创建了形状73000x8000的机器上的数据帧和我的记忆飙升至4.4 GB,所以我不会有崩溃感到惊讶。也就是说,如果你确实需要用索引列表创建一个新数组,那么你的运气不好。但是,修改原来的数据框,你应该能够在一个时间来修改数据框一行或几片排在同一时间以速度为代价,如:
for i in arbitrary_list_of_indices:
df.ix[i] = new_values
顺便说一句,你可以尝试工作直接关闭numpy数组,我感觉有更清晰的描述哪些操作导致副本vs视图。你可以总是从数组中创建一个DataFrame,几乎没有任何内存开销,因为它只是创建一个对原始数组的引用。
在numpy中索引也很快,即使没有切片。这里有一个简单的测试用例:
In [66]: df
Out[66]:
0 1 2 3
0 3 14 5 1
1 9 19 14 4
2 5 4 5 5
3 13 14 4 7
4 8 12 3 16
5 15 3 17 12
6 11 0 12 0
In [68]: df.ix[[1,3,5]] # fancy index version
Out[68]:
0 1 2 3
1 9 19 14 4
3 13 14 4 7
5 15 3 17 12
In [69]: df.ix[1:5:2] # sliced version of the same
Out[69]:
0 1 2 3
1 9 19 14 4
3 13 14 4 7
5 15 3 17 12
In [71]: %timeit df.ix[[1,3,5]] = -1 # use fancy index version
1000 loops, best of 3: 251 µs per loop
In [72]: %timeit df.ix[1:5:2] = -2 # faster sliced version
10000 loops, best of 3: 157 µs per loop
In [73]: arr = df.values
In [74]: arr
Out[74]:
array([[ 3, 14, 5, 1],
[-2, -2, -2, -2],
[ 5, 4, 5, 5],
[-2, -2, -2, -2],
[ 8, 12, 3, 16],
[-2, -2, -2, -2],
[11, 0, 12, 0]])
In [75]: %timeit arr[[1,3,5]] = -1 # much faster than DataFrame
The slowest run took 23.49 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 4.56 µs per loop
In [77]: %timeit arr[1:5:2] = -3 # really fast but restricted to slicing
The slowest run took 19.46 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 821 ns per loop
祝你好运!
你试过'to_sparse'方法吗? http://pandas.pydata.org/pandas-docs/stable/sparse.html – breucopter
尝试一下 - 似乎需要一段时间。 to_sparse方法的结果数据框可以很容易地进行子集化吗?编辑:在我的73000x8000数据帧上使用to_sparse使我的电脑崩溃 –
你试过了:'list_of_inds = pd.Index(list_of_inds); df.ix [list_of_inds]'? – MaxU