在保留内部订单的同时,将数据框架改组



i具有包含预处理数据的数据框架,因此每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)还不够,因为它会破坏序列。

解决方案,感谢 @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)])

这是您需要的, np.random.choice

d={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)])
yourdf
Out[986]: 
   col1 col2
4     5    e
5     6    f
6     7    g
7     8    h
0     1    a
1     2    b
2     3    c
3     4    d

您可以通过...将索引分组为四组,然后将其划分。

示例:

df = pd.DataFrame(np.random.randint(10, size=(12, 2)))
    a  b
0   5  4
1   7  7
2   7  8
3   8  4
4   9  4
5   9  0
6   1  5
7   4  1
8   0  1
9   5  6
10  1  3
11  9  2
new_index = np.array(df.index).reshape(-1, 4)
np.random.shuffle(new_index)  # shuffles array in-place
df = df.loc[new_index.reshape(-1)]
    a  b
8   0  1
9   5  6
10  1  3
11  9  2
4   9  4
5   9  0
6   1  5
7   4  1
0   5  4
1   7  7
2   7  8
3   8  4

正如您所说的序列4的数据时,数据框架的长度应为4的倍数。如果您的数据以3为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 col2
0     1    a
1     2    b
2     3    c
3     4    d
4     5    e
5     6    f
6     7    g
7     8    h
>>> df.shape[0]
8

创建改组的列表:

>>> np_range = np.arange(0,df.shape[0])
>>> np_range
array([0, 1, 2, 3, 4, 5, 6, 7])

重塑和改组:

>>> np_range1 = np.reshape(np_range,(df.shape[0]/4,4))
>>> np_range1
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
>>> np.random.shuffle(np_range1)
>>> np_range1
array([[4, 5, 6, 7],
       [0, 1, 2, 3]])
>>> np_range2 = np.reshape(np_range1,(df.shape[0],))
>>> np_range2
array([4, 5, 6, 7, 0, 1, 2, 3])

选择数据:

>>> new_df = df.loc[np_range2]
>>> new_df
   col1 col2
4     5    e
5     6    f
6     7    g
7     8    h
0     1    a
1     2    b
2     3    c
3     4    d

我希望这会有所帮助!谢谢!

最新更新