随机选择两个值,而无需在数据帧中重复

时间:2019-04-13 17:35:56

标签: python pandas

考虑一个具有df列和N行的数据帧M

>>> df = pd.DataFrame(np.random.randint(1, 10, (10, 5)), columns=list('abcde'))
>>> df
   a  b  c  d  e
0  4  4  5  5  7
1  9  3  8  8  1
2  2  8  1  8  5
3  9  5  1  2  7
4  3  5  8  2  3
5  2  8  8  2  8
6  3  1  7  2  6
7  4  1  5  6  3
8  5  4  4  9  5
9  3  7  5  6  6

我想随机选择两列,然后随机选择一个特定的行(这将为我提供同一行的两个值)。我可以使用

>>> df.sample(2, axis=1).sample(1,axis=0)
   e  a
1  3  5

我想像下面这样K次执行该操作:

>>> for i in xrange(5):
...     df.sample(2, axis=1).sample(1,axis=0)
...
   e  a
1  3  5
   d  b
2  1  9
   e  b
4  8  9
   c  b
0  6  5
   e  c
1  3  5

我想确保在任何试验中都不要选择相同的两个值(通过选择相同的两列和同一行)。我将如何实现?

然后,我还要对每个试验中的两个选定值执行按位XOR操作。例如3 ^ 5,1 ^ 9,..并计算所选值中的所有位差。

1 个答案:

答案 0 :(得分:4)

您可以按2列元组创建所有索引的列表。然后从中随机选择而不替换。

样本数据

import pandas as pd
import numpy as np
from itertools import combinations, product

np.random.seed(123)
df = pd.DataFrame(np.random.randint(1, 10, (10, 5)), columns=list('abcde'))
#df = df.reset_index() #if index contains duplicates

代码

K = 5
choices = np.array(list(product(df.index, combinations(df.columns, 2))))
idx = choices[np.r_[np.random.choice(len(choices), K, replace=False)]]

#array([[9, ('a', 'e')],
#       [2, ('a', 'e')],
#       [1, ('a', 'c')],
#       [3, ('b', 'e')],
#       [8, ('d', 'e')]], dtype=object)

然后,您可以决定所需输出的精确度,但是类似于您所显示的内容:

pd.concat([df.loc[myid[0], list(myid[1])].reset_index().T for myid in idx])
#       0  1
#index  a  e
#9      4  8
#index  a  e
#2      1  1
#index  a  c
#1      7  1
#index  b  e
#3      2  3
#index  d  e
#8      5  7