我有一个名为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]
最后一行代码无限期挂起.有没有更好的办法做这件事?
我有一个名为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