2016-07-06 73 views
2

在典型蟒數據幀,這很容易基於索引選擇所需要的行數:從稀疏數據幀選擇行由索引位置

df.ix[list_of_inds] or df.loc[list_of_inds] 

然而,使用此方法來取大,稀疏數據幀的主要子集(73,000行,特別是8000列)似乎非常密集 - 我的記憶力開始上升,我的電腦崩潰。

我也採用了一系列這樣的發現,索引..

df.ix[1:N] 

工作正常,而使用這樣的索引列表...

df.ix[np.arange(1,N)] 

是什麼使內存過載。

是否有另一種方法從稀疏數據框中選擇計算更簡單的行?或者,我可以將此數據幀轉換爲實際的稀疏矩陣...

sparse_df = scipy.sparse.csc(df) 

並只選擇我想要的索引?

+0

你試過'to_sparse'方法嗎? http://pandas.pydata.org/pandas-docs/stable/sparse.html – breucopter

+0

嘗試一下 - 似乎需要一段時間。 to_sparse方法的結果數據框可以很容易地進行子集化嗎?編輯:在我的73000x8000數據幀上使用to_sparse使我的電腦崩潰 –

+0

你試過了:'list_of_inds = pd.Index(list_of_inds); df.ix [list_of_inds]'? – MaxU

回答

0

您面臨的問題可能與查看與複製語義有關。

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 

祝你好運!