小编Sid*_*war的帖子

通过分层采样将 pandas Dataframe 分成 4 部分

我想通过分层采样将 Dataframe 分成 4 部分。确保“B”列中的所有类别都应出现在每个块中。如果任何类别没有足够的记录用于所有块,请将相同的记录复制到剩余的块中。

df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                             'foo', 'bar', 'foo', 'foo',
                         'foo', 'bar', 'foo', 'bar',
                             'foo', 'bar', 'foo', 'foo', 'bar'],
                       'B' : ['one', 'one', 'two', 'three',
                             'two', 'two', 'one', 'three',
                             'one', 'one', 'two', 'three',
                             'two', 'two', 'one', 'three', 'four'],
                       'C' : np.random.randn(17), 'D' : np.random.randn(17)})

print(df)

      A      B         C         D
0   foo    one  0.960627  0.318723
1   bar    one  0.269439 -0.945565
2   foo    two  0.210376  0.765680
3   bar  three -0.375095 -1.617334
4   foo    two -1.910716 …
Run Code Online (Sandbox Code Playgroud)

dataframe python-3.x pandas

5
推荐指数
1
解决办法
547
查看次数

标签 统计

dataframe ×1

pandas ×1

python-3.x ×1