在pandas DataFrame中随机播放一个行列块

问题描述 投票:0回答:2

我想知道如何将DataFrame中指定的“矩形”值中的值随机地移动到位。例如,假设我想要将第4列到第7列和第12行到第18行(包括第4列)定义的数据矩形中的值混洗。我们的想法是对这些单元格中的值进行加扰,而不会影响矩形外的值。

python pandas
2个回答
0
投票

你可以在底层的NumPy数组上使用numpy.random.shuffle()

通过混洗其内容来就地修改序列。

df = pd.DataFrame(np.arange(20).reshape(5, 4))

np.random.shuffle(df.values[1:3, 1:3])

df  # see [[9, 10], [5, 6]]

    0   1   2   3
0   0   1   2   3
1   4   9  10   7
2   8   5   6  11
3  12  13  14  15
4  16  17  18  19

0
投票

一种方法是使用samplefrac=1,首先我“切片”我的数据帧只获得我正在加扰的形状,然后将数据帧切片重新整形为1-D,然后调用100%分数的样本方法,并重新塑造回来原始并复制回原始数据帧:

df = pd.DataFrame(np.arange(100).reshape(5,-1))
print(df)

输入df:

   0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19
0   0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19
1  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39
2  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59
3  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79
4  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99

#Shuffle first region columns 4 to 7    
df.iloc[:, 4:8] = (df.iloc[:,4:8].stack().sample(frac=1)
                     .set_axis(df.iloc[:, 4:8].stack().index, inplace=False)
                     .unstack())

#Shuffle second region columns 12 to 18
df.iloc[:, 12:19] = (df.iloc[:,12:19].stack().sample(frac=1)
                       .set_axis(df.iloc[:, 12:19].stack().index, inplace=False)
                       .unstack())

print(df)

输出df:

   0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19
0   0   1   2   3   7  47  65  46   8   9  10  11  18  75  32  73  34  56  37  19
1  20  21  22  23  66  24   4  67  28  29  30  31  92  55  54  97  76  93  74  39
2  40  41  42  43  26  45  27  25  48  49  50  51  12  17  16  38  98  57  96  59
3  60  61  62  63  86  84   6   5  68  69  70  71  14  78  15  53  77  35  94  79
4  80  81  82  83  85  64  87  44  88  89  90  91  95  33  36  52  13  58  72  99
© www.soinside.com 2019 - 2024. All rights reserved.