熊猫随机播放最后N行

时间:2018-12-22 17:15:06

标签: python pandas

如何在大熊猫数据框中随机播放最后N行?当我说“随机”时,我的意思是随机更改行的顺序。到目前为止,这是我尝试过的。我不知道如何正确重置索引。

import pandas as pd
import numpy as np
dat = pd.DataFrame({'d1': np.linspace(0, 1, 10)})
pd.concat([dat[:5], dat[5:].sample(frac=1).reset_index(drop=True)])

输出:

         d1
0  0.000000
1  0.111111
2  0.222222
3  0.333333
4  0.444444
0  0.777778
1  0.666667
2  0.888889
3  1.000000
4  0.555556

2 个答案:

答案 0 :(得分:1)

对于默认索引,将参数ignore_index=True添加到concat

dat = pd.DataFrame({'d1': np.linspace(0, 1, 10)})
df = pd.concat([dat[:5], dat[5:].sample(frac=1)], ignore_index=True)

另一种解决方案是仅将sample用于最后一行,并用values分配回numpy array以防止索引对齐:

dat.iloc[5:] = dat.iloc[5:].sample(frac=1).values

np.random.shuffle正常运行的Numpy解决方案:

np.random.shuffle(dat.iloc[5:].values)

print (df)
         d1
0  0.000000
1  0.111111
2  0.222222
3  0.333333
4  0.444444
5  0.666667
6  0.888889
7  1.000000
8  0.555556
9  0.777778

答案 1 :(得分:1)

您可以直接使用shuffle

import pandas as pd
import numpy as np

np.random.seed(42)

dat = pd.DataFrame({'d1': np.linspace(0, 1, 10)})
np.random.shuffle(dat.values[5:])
print(dat)

输出

d1
0  0.000000
1  0.111111
2  0.222222
3  0.333333
4  0.444444
5  0.666667
6  1.000000
7  0.777778
8  0.555556
9  0.888889

或者,如果您愿意,permutation

import pandas as pd
import numpy as np

dat = pd.DataFrame({'d1': np.linspace(0, 1, 10)})
dat.values[5:] = np.random.permutation(dat.values[5:])

print(dat)

输出

         d1
0  0.000000
1  0.111111
2  0.222222
3  0.333333
4  0.444444
5  0.555556
6  0.888889
7  0.777778
8  1.000000
9  0.666667
相关问题