我有一个名为X_it的数据帧,形状为(2667913,42)

我正在try 使用以下代码从该数据帧中进行采样:

import numpy as np

np.random.seed(42)

sel_idx = X_it.sample(frac=0.1).index

X = X_it.loc[sel_idx]

最后一行代码无限期挂起.有没有更好的办法做这件事?

推荐答案

很难确切知道发生了什么,但我怀疑是对sample的错误使用和重复索引的组合.

为什么您要sample行,然后获得输出的索引,然后用它再次切片原始数据帧呢?

让我们看看可能会出什么问题.

sample已经为您提供了一个DataFrame.再次编制索引是没有用的:

df = pd.DataFrame({'A': range(10),
                   'B': range(10)})
print(df)

   A  B
0  0  0
1  1  1
2  2  2
3  3  3
4  4  4
5  5  5
6  6  6
7  7  7
8  8  8
9  9  9

# now let's sample
out = df.sample(frac=0.3)
print(out)

   A  B
9  9  9
1  1  1
0  0  0


# now let's index again
print(out.loc[out.index])

   A  B
9  9  9
1  1  1
0  0  0

第二步显然毫无用处,但也没有造成太大的伤害.

Now let's assume that you have duplicated indices in the input:

   A  B
0  0  0
0  1  1
0  2  2
0  3  3
0  4  4
0  5  5
0  6  6
0  7  7
0  8  8
0  9  9

如果我们只有sample岁,一切都很好:

out = df.sample(frac=0.3)
print(out)

   A  B
0  5  5
0  9  9
0  2  2

但如果我们以此为索引,现在它是糟糕的,all rows are selected as many times as there are duplicates.在本例中,对于采样中间层中的n行,您将获得n**2行.对于大输入来说,这是相当大的,并且可能是超时的原因:

print(out.loc[out.index])
   A  B
0  5  5
0  9  9
0  2  2
0  5  5
0  9  9
0  2  2
0  5  5
0  9  9
0  2  2

Python相关问答推荐

根据网格和相机参数渲染深度

非常奇怪:tzLocal.get_Localzone()基于python3别名的不同输出?

使用@ guardlasses. guardlass和注释的Python继承

对象的`__call__`方法的setattr在Python中不起作用'

把一个pandas文件夹从juyter笔记本放到堆栈溢出问题中的最快方法?

为一个组的每个子组绘制,

如何使Matplotlib标题以图形为中心,而图例框则以图形为中心

需要帮助重新调整python fill_between与数据点

无论输入分辨率如何,稳定扩散管道始终输出512 * 512张图像

如何在达到end_time时自动将状态字段从1更改为0

Flash只从html表单中获取一个值

如何使用OpenGL使球体遵循Python中的八样路径?

以异步方式填充Pandas 数据帧

Python将一个列值分割成多个列,并保持其余列相同

numpy数组和数组标量之间的不同行为

应用指定的规则构建数组

解决Geopandas和Altair中的正图和投影问题

如何获取包含`try`外部堆栈的`__traceback__`属性的异常

用来自另一个数据框的列特定标量划分Polars数据框中的每一列,

如何在Python中从html页面中提取html链接?