Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Pandas-groupby:高效地提取索引_Python_Pandas_Numpy_Pandas Groupby_Point Clouds - Fatal编程技术网

Python Pandas-groupby:高效地提取索引

Python Pandas-groupby:高效地提取索引,python,pandas,numpy,pandas-groupby,point-clouds,Python,Pandas,Numpy,Pandas Groupby,Point Clouds,我正在尝试有效地将三维点云拆分为多个二维平铺/分段 结合使用numpy的searchsorted()和pandas groupby()函数,我能够以令人满意的速度将数据分组 例如: import numpy as np import pandas as pd import time scale=100 n_points= 1000000 n_tiles = 1000000 pos = np.empty((n_points,3)) pos[:,0]=np.random.random(n_poi

我正在尝试有效地将三维点云拆分为多个二维平铺/分段

结合使用numpy的searchsorted()和pandas groupby()函数,我能够以令人满意的速度将数据分组

例如:

import numpy as np
import pandas as pd
import time

scale=100
n_points= 1000000
n_tiles = 1000000

pos = np.empty((n_points,3))
pos[:,0]=np.random.random(n_points)*scale
pos[:,1]=np.random.random(n_points)*scale
pos[:,2]=np.random.random(n_points)

df = pd.DataFrame(pos)

# create bounds for each segment
min_bound,max_bound = 0,scale
x_segment_bounds,xstep = np.linspace(min_bound, max_bound, num=n_tiles**0.5,retstep = True)
x_segment_bounds[0]=x_segment_bounds[0]+xstep/2
y_segment_bounds,ystep = np.linspace(min_bound, max_bound, num=n_tiles**0.5,retstep=True)
y_segment_bounds[0]=y_segment_bounds[0]+ystep/2

# sort into bins
time_grab = time.clock()
bins_x = np.searchsorted(x_segment_bounds, pos[:, 0])
bins_y = np.searchsorted(y_segment_bounds, pos[:, 1])
print("Time for binning: ", time.clock()-time_grab)

df["bins_x"] = bins_x.astype(np.uint16)
df["bins_y"] = bins_y.astype(np.uint16)

# group points
time_grab = time.clock()
segments = df.groupby(['bins_x', 'bins_y'])
print("Time for grouping: ", time.clock()-time_grab)
产生:

Time for binning:  0.1390
Time for grouping:  0.0043
我遇到的问题是如何有效地访问pandas groupby对象中属于每个组的点索引

例如,在每个组中循环是非常低效的:

segment_indices = []
for i,segment in enumerate(segments):
    segment_indices.append(segment[1].index.values)
大约需要70秒

我找到了检索索引的方法:

segments = df.groupby(['bins_x', 'bins_y']).apply(lambda x: x.index.tolist()) 
这需要约10秒,但是与装箱和分组功能相比,速度仍然相当慢。由于我只是试图将数据复制到一个新的数组或列表中,而不是实际对其执行任何计算,因此我希望效率更高。我希望速度至少与装箱和分组操作类似


我很好奇是否有更有效的方法从groupby对象提取索引(或任何信息)?或者,是否有其他不使用熊猫的分割/分组点的方法,例如numpy或scipy替代方法

请注意GroupBy性能:请注意“在需要之前不会进行拆分。创建GroupBy对象只会验证您是否通过了有效的映射。”因此调用
GroupBy()
总是很快的;后续的聚合函数将取决于输入数据的大小。我明白了,这是有道理的。因此,在调用后续函数之前,实际上不会执行任何计算。我确实认为将数据分成100万组似乎非常快。在这种情况下,我可能会更深入地研究numpy替代品。。