在数据框中混洗多列

Shuffling Multi Column in data frame

我有一个这样的数据框:

'a'                   'b'    'c'    'd'               'e'  'f'
'hello.text'           1      2      'hello2.text'     2   10
'hello3.text'          5      8      'hello4.text'     8   15

现在我需要随机排列 'a'、'b'、'c' 列。 像这样的事情:

'a'                   'b'    'c'    'd'               'e'  'f'
'hello3.text'          5      8      'hello2.text'     2   10
'hello.text'           1      2      'hello4.text'     8   15

我该怎么做?

使用 np.random.permutationDataFrame.apply 分别处理每一列,因为不同类型的数据:

cols = ['a','b','c']

df[cols] = df[cols].apply(lambda x: np.random.permutation(x))
print (df)
               a  b  c              d  e   f
0   'hello.text'  5  2  'hello2.text'  2  10
1  'hello3.text'  1  8  'hello4.text'  8  15

'a', 'b', 'c' 列随机排列在一起,意味着只对这些特定列的行进行随机排列?如果是,那么以下就是您所需要的:

cols = ['a','b','c']
df[cols] = df[cols].sample(frac=1.0, random_state=0).reset_index(drop=True)
print(df)

            a  b  c            d  e   f
0  hello3.txt  5  8  hello2.text  2  10
1  hello.text  1  2  hello4.text  8  15

您可以使用 random_state 参数控制随机化。