数据帧中的多列混洗

2024-06-06 05:36:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据框:

'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

我该怎么做?你知道吗


Tags: 数据texthello事情hello2hello4hello3
2条回答

'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参数来控制随机化。你知道吗

使用np.random.permutation^{}分别处理每一列,因为不同类型的数据:

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

相关问题 更多 >