Skip to main content
 首页 » 编程设计

python之给定数据分布离散化 Pandas 的列

2024年10月01日8kuangbin

我有一个 pandas 的数据框,其中一列包含从 0 到 50 的真实数据。它们分布不均。

我可以使用以下方式获取分发:

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

我想做的是将每个值替换为其所属的 bin 编号。

为此,这是可行的:

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

但是,对于包含 4 百万行以上的数据帧,它非常慢(50 分钟)。我正在寻找一种更有效的方法。你们有更好的主意吗?

请您参考如下方法:

只需使用 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