2017-06-08 21 views
2

我有一個熊貓數據框,其中一列包含從0到50的實際數據。它們不是均勻分佈的。給出數據分佈的Discretisize Pandas'列

我可以用得到的分佈:

hist, bins = np.histogram(df["col"]) 

我想什麼做的是替換爲箱數量就落在每個值

要做到這一點,這是工作:

for i in range(len(df["speed_array"])): 
    df["speed_array"].iloc[i] = np.searchsorted(bins, df["speed_array"].iloc[i]) 

但是,對於數據行數超過4百萬行的數據幀來說,它非常慢(50分鐘)。我正在尋找一種更有效的方法來解決這個問題。你們有更好的主意嗎?

回答

2

對整個基礎數組數據只需使用np.searchsorted -

df["speed_array"] = np.searchsorted(bins, df["speed_array"].values) 

運行測試 -

In [140]: # 4 million rows with 100 bins 
    ...: df = pd.DataFrame(np.random.randint(0,1000,(4000000,1))) 
    ...: df.columns = [['speed_array']] 
    ...: bins = np.sort(np.random.choice(1000, size=100, replace=0)) 
    ...: 

In [141]: def searchsorted_app(df): 
    ...:  df["speed_array"] = np.searchsorted(bins, df["speed_array"].values) 
    ...:  

In [142]: %timeit searchsorted_app(df) 
10 loops, best of 3: 15.3 ms per loop 
+1

雖然我夢到簡單!謝謝! – Xema

+0

@Xema很高興知道在原來的'50分鐘'標記加速:) – Divakar

+0

嗯,這是非常瞬間! – Xema

相關問題