<p>我希望我没有提出一个对你的例子过于具体的解决方案。但是,如果可行,您可以创建每个排列,然后删除不符合您的条件的排列。然后您可以直接使用该样本,也可以从结果排列中随机抽取样本。在</p>
<p>下面的代码是受上面的示例启发的。我意识到我使用的起始假设略有不同:</p>
<pre><code>df = pd.DataFrame( list(itertools.product([1,2,3,4], [1,2,3,4])), columns = ['X','Y'])
print df
X Y
0 1 1
1 1 2
2 1 3
3 1 4
4 2 1
5 2 2
6 2 3
7 2 4
8 3 1
9 3 2
10 3 3
11 3 4
12 4 1
13 4 2
14 4 3
15 4 4
</code></pre>
<p>然后设置您感兴趣的条件:</p>
^{pr2}$
<p><strong><em>编辑</em></strong>:
我会把上面所有的组合垃圾留在那里,因为别人可能会觉得有用。但在评论中聊天后,我想我有一个可能的解决办法。在</p>
<p>您似乎可以进行排列,然后将排列的数据帧分成两个子集:</p>
<ol>
<li>不符合条件的数据(即X==Y)</li>
<li>符合条件的数据(X!=Y)</li>
</ol>
<p>然后我们可以取第一个子集,再简单地置换它。子集1应该比子集2小得多。我们只是递归地这样做,创建一组符合条件的记录应该非常容易和快速。在</p>
<p>当然,我们必须处理只有一行匹配的情况。在</p>
<p>我实施了一个示例解决方案:</p>
<p>设置一些与实际数据大小相似的播放数据:</p>
<pre><code>np.random.seed(3)
n=14000000
df = pd.DataFrame({'X' : np.random.randint(2000000, size=n),
'Y' : np.random.randint(2000000, size=n)})
</code></pre>
<p>示例数据将以一些重复的行开始,但这没关系。让我们创建shuffle函数:</p>
<pre><code>def permuteDataFrame(inDf):
permutedDf = pd.DataFrame({'X' : np.random.permutation(inDf.X),
'Y' : np.random.permutation(inDf.Y)})
# check for dupes
clash = permutedDf[permutedDf.X == permutedDf.Y]
if clash.shape[0] > 1: #repermuting can't work if only one row has a match
clash = permutedDf[permutedDf.X == permutedDf.Y].copy()
noclash = permutedDf[permutedDf.X != permutedDf.Y].copy()
# recursion FTW: run the clashes back through this algo
clash = permuteDataFrame(clash)
permutedDf = pd.concat([clash, noclash ])
if clash.shape[0] == 1: # handle the single match problem
# solving the single match by grabbing the single match plus a random other record and permuting
# get the vector of bools that indicate matches
clashIndex = permutedDf.X == permutedDf.Y
# randomly make another one True
ilocToSwap = np.random.randint(permutedDf.shape[0]) # random record location to swap
indexOfClashes.iloc[ilocToSwap] = True
clash = permutedDf[indexOfClashes]
# recursion FTW: run the clashes back through this algo
clash = permuteDataFrame(clash)
permutedDf = pd.concat([clash, noclash ])
return permutedDf
</code></pre>
<p>在我的Mac电脑上,一个简单的排列需要5.3秒。新的<code>permuteDataFrame()</code>函数需要5.8秒。即使在你的机器上花了8秒,也能在2.2小时内得到1000个。那可能有用。在</p>