我有一个 pandas 的数据框,其中一列包含从 0 到 50 的真实数据。它们分布不均匀。
我可以使用以下方式获取发行版:
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])
但是,对于超过 400 万行的数据帧,速度相当慢(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
关于python - 考虑到数据分布,离散化 Pandas 的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44435458/