在保持内部顺序的同时打乱 DataFrame

我有一个包含预处理数据的数据框,这样每 4 行是一个序列(稍后将被重塑并用于 lstm 训练)。


我想打乱数据框,但我想保持每个行序列不变。例如: a = [1,2,3,4,10,11,12,13,20,21,22,23]将变成类似:a = [20,21,22,23,1,2,3,4,10,11,12,13]。


df.sample(frac=1) 是不够的,因为它会破坏序列。


Solution , thanks to @Wen-Ben:


seq_length = 4 

length_array = np.arange((df.shape[0]//seq_length)*seq_length)

trunc_data = df.head((df.shape[0]//seq_length)*seq_length)

d = {x : y for x, y in trunc_data.groupby(length_array//seq_length)}

yourdf = pd.concat([d.get(x) for x in np.random.choice(len(d),len(d.keys()),replace=False)])



炎炎设计
浏览 304回答 3
3回答

天涯尽头无女友

这是你需要的吗 np.random.choiced={x : y for x, y in df.groupby(np.arange(len(df))//4)}yourdf=pd.concat([d.get(x) for x in np.random.choice(len(d),2,replace=False)])yourdfOut[986]:    col1 col24     5    e5     6    f6     7    g7     8    h0     1    a1     2    b2     3    c3     4    d

三国纷争

您可以通过以下方式按 4 组重新洗牌... 将索引分组为 4 组,然后对其进行洗牌。例子:df = pd.DataFrame(np.random.randint(10, size=(12, 2)))    a  b0   5  41   7  72   7  83   8  44   9  45   9  06   1  57   4  18   0  19   5  610  1  311  9  2new_index = np.array(df.index).reshape(-1, 4)np.random.shuffle(new_index)  # shuffles array in-placedf = df.loc[new_index.reshape(-1)]    a  b8   0  19   5  610  1  311  9  24   9  45   9  06   1  57   4  10   5  41   7  72   7  83   8  4

BIG阳

如您所说,您有4个序列的数据,那么数据帧的长度应该是4的倍数。如果您的数据是3个序列,请在代码中将4更改为3。>>> import pandas as pd>>> import numpy as np创建表:>>> df = pd.DataFrame({'col1':[1,2,3,4,5,6,7,8],'col2':['a','b','c','d','e','f','g','h']})>>> df   col1 col20     1    a1     2    b2     3    c3     4    d4     5    e5     6    f6     7    g7     8    h>>> df.shape[0]8创建洗牌列表:>>> np_range = np.arange(0,df.shape[0])>>> np_rangearray([0, 1, 2, 3, 4, 5, 6, 7])重塑和洗牌:>>> np_range1 = np.reshape(np_range,(df.shape[0]/4,4))>>> np_range1array([[0, 1, 2, 3],       [4, 5, 6, 7]])>>> np.random.shuffle(np_range1)>>> np_range1array([[4, 5, 6, 7],       [0, 1, 2, 3]])>>> np_range2 = np.reshape(np_range1,(df.shape[0],))>>> np_range2array([4, 5, 6, 7, 0, 1, 2, 3])选择数据:>>> new_df = df.loc[np_range2]>>> new_df   col1 col24     5    e5     6    f6     7    g7     8    h0     1    a1     2    b2     3    c3     4    d我希望这有帮助!谢谢!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python