gpt4 book ai didi

python - 随机选择两个值而不在数据框中重复

转载 作者:行者123 更新时间:2023-11-28 22:11:27 24 4
gpt4 key购买 nike

考虑一个包含 N 列和 M 行的数据框 df:

>>> 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

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

然后我还想对每次试验中的两个选定值执行按位异或运算。例如,3 ^ 5、1 ^ 9、.. 并计算所选值中的所有位差。

最佳答案

您可以通过 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

关于python - 随机选择两个值而不在数据框中重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55668175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com