Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 对数据帧中的行进行随机化,以便相同的值不会出现';不要连续重复两次_Python_Jupyter Notebook - Fatal编程技术网

Python 对数据帧中的行进行随机化,以便相同的值不会出现';不要连续重复两次

Python 对数据帧中的行进行随机化,以便相同的值不会出现';不要连续重复两次,python,jupyter-notebook,Python,Jupyter Notebook,我有一个数据框,看起来像这样(见附图) 我想实现一个非常简单的事情:洗牌这个数据帧的行,但有一个限制,即“Identity”列中的数字在一行中不会出现两次(例如,如果我们有一个序列112233,这将是一个可接受的洗牌:123123,但这不会:123321,因为有两个数字3出现在一行中) 我迄今为止“最成功”的尝试是: def shuffling(x): spreadsheetEmpty = pd.DataFrame(columns=['NeutralImage', 'Emotio

我有一个数据框,看起来像这样(见附图)

我想实现一个非常简单的事情:洗牌这个数据帧的行,但有一个限制,即“Identity”列中的数字在一行中不会出现两次(例如,如果我们有一个序列112233,这将是一个可接受的洗牌:123123,但这不会:123321,因为有两个数字3出现在一行中)

我迄今为止“最成功”的尝试是:

def shuffling(x):    
    spreadsheetEmpty = pd.DataFrame(columns=['NeutralImage', 'EmotionalImage', 'Group', 'Condition', 'Emotion', 'Identity', 'Gender', 'trigger']) #Create an empty data frame - same columns as the original
    for index in range(0,len(x)-1): 
        while x['Identity'].iloc[index] == x['Identity'].iloc[index+1]: #if the identity in that row is the same as in the next one, shuffle again
            x = x.sample(frac=1).reset_index(drop=True 
        else: #If we don't have two identities right next to each other:
            spreadsheet_final = spreadsheetEmpty.append(x) #Fill in the empty spreadsheet from the beginning with a pseudorandomized one
            return(spreadsheet_final)
然而,使用这段代码我无法实现我想要的,因为它确保只有前两个数字不会彼此相邻重复,并忽略列中的其余值

是否有人建议如何修改此函数以检查数据框中的所有行是否重复

提前谢谢你


同时,我设法解决了这个问题,因此成功的函数现在看起来如下所示:

def洗牌(x):
#创建一个空数据帧
spreadsheetEmpty=pd.DataFrame(列=['NeutralImage','EmotionalImage','Group','Condition','Emotional','Identity','Gender','trigger','FixCrossColor1','FixCrossColor2','Combination'])
xshuffle=x.sample(frac=1)。重置索引(drop=True)#第一次洗牌行
而任何(范围(0,len(xshuffle)-1)内的标签的xshuffle['Identity'].iloc[label]==xshuffle['Identity'].iloc[label+1]:#如果标识值在数据帧中的任何位置连续重复两次,则再次洗牌
xshuffle=x.sample(frac=1)。重置索引(drop=True)
否则:#如果我们没有两个相邻的身份,请填写空的电子表格
电子表格\u final=spreadsheetEmpty.append(xshuffle)
打印(电子表格\最终版)

您真的需要洗牌还是只洗牌以分离重复项?重复项的比例是多少?此电子表格用于研究,因此需要洗牌行以实现刺激的随机性(情绪图像列中的图像),它的作用不仅仅是分离“重复项”。此外,从技术上讲,这里没有重复项(忽略图像名称,我只使用它们进行测试)-同一个人有三个不同的图像(这就是为什么在标识列中有3个数字的块)我只是不希望同一个人的图像连续出现两次,这就是我使用该功能的目的。希望我说得清楚,谢谢!