python - 如何从数据帧中但从每个标签中随机删除行?

标签 python python-3.x pandas numpy machine-learning

这是一个机器学习项目。

我有一个数据框,其中 5 列作为特征,1 列作为标签(图 A)。

我想从每个标签中随机删除 2 行。 因此,由于有 12 行(每个标签 4 行);我最终会得到 6 行(每个标签 2 行)(图 B)。

我该怎么做?仅使用 numpy 会更容易吗?

图A

enter image description here

图B

enter image description here

这是我的代码:

# THIS IS FOR FIGURE A
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(12, 5))

label=np.array([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3])

df['label'] = label
df.index=['s1', 's1', 's1', 's1', 's2', 's2', 's2', 's2', 's3', 's3', 's3', 's3']
df

#THIS IS MY ATTEMPT FOR FIGURE B
dfs = df.sample(n=2)
dfs

最佳答案

使用groupby.apply:

df.groupby('label', as_index=False).apply(lambda x: x.sample(2)) \
                                   .reset_index(level=0, drop=True)
Out: 
           0         1         2         3         4  label
s1  0.433731  0.886622  0.683993  0.125918  0.398787      1
s1  0.719834  0.435971  0.935742  0.885779  0.460693      1
s2  0.324877  0.962413  0.366274  0.980935  0.487806      2
s2  0.600318  0.633574  0.453003  0.291159  0.223662      2
s3  0.741116  0.167992  0.513374  0.485132  0.550467      3
s3  0.301959  0.843531  0.654343  0.726779  0.594402      3

我认为更简洁的方法是理解:

pd.concat(g.sample(2) for idx, g in df.groupby('label'))

这会产生相同的结果:

           0         1         2         3         4  label
s1  0.442293  0.470318  0.559764  0.829743  0.146971      1
s1  0.603235  0.218269  0.516422  0.295342  0.466475      1
s2  0.569428  0.109494  0.035729  0.548579  0.760698      2
s2  0.600318  0.633574  0.453003  0.291159  0.223662      2
s3  0.412750  0.079504  0.433272  0.136108  0.740311      3
s3  0.462627  0.025328  0.245863  0.931857  0.576927      3

关于python - 如何从数据帧中但从每个标签中随机删除行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41067425/

相关文章:

python - 如何从大型数据集中提取每天每小时的 500 个条目?

python - 有没有办法在 Python 中为最小值和最大值返回自定义值?

Python:我是否必须使用 else 语句(除非代码强制)?

Python 导入搜索路径 : what happens first?

python - 根据其他三列的多数值设置 pandas 数据框获胜者列值

python - Pandas 基于行的计算和迭代

python - 将参数复制为常量值?

python - 如何使用python从文件中读取复数

python,返回位置和文件大小

python - 无法使用python将元素列表写入文件