简体   繁体   English

在DataFrame中随机播放部分行

[英]Shuffle portion of rows in DataFrame

I have come across some previous posts regarding how to shuffle row values ( Randomizing/Shuffling rows in a dataframe in pandas ). 我之前发过一些关于如何对行值进行混洗的帖子( 在pandas中的数据帧中随机化/随机排列 )。 For me though, I was wondering how to shuffle a portion of those rows, rather than the entirety of these rows. 但对我来说,我想知道如何改变这些行的一部分,而不是整行这些行。

I made a quick dataframe here: 我在这里做了一个快速的数据框:

df = pd.DataFrame(np.random.randn(10, 5), columns=list('ABCDE'))

Is there a way to re-work this such that for each row, the values in columns B,C,and D are shuffled while the values in columns A and E remain in the same location? 有没有办法重新处理这个问题,对于每一行,列B,C和D中的值是否混洗,而列A和E中的值保持在同一位置?

You can use slicing in the shuffle command: 您可以在shuffle命令中使用切片:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10, 5), columns=list('ABCDE'))
print df

A=df.values
_= [np.random.shuffle(i) for i in A[: ,1:4]]

df2=pd.DataFrame(A, columns=list('ABCDE'))
print df2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM