如何从每个标签中随机删除数据框的行?

这是一个机器学习项目。

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

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

我该如何操作?使用仅numpy会更容易吗?

图A

enter image description here

图B

enter image description here

这是我的代码:

# 这是图A的代码import pandas as pdimport numpy as npdf = pd.DataFrame(np.random.rand(12, 5))label=np.array([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3])df['label'] = labeldf.index=['s1', 's1', 's1', 's1', 's2', 's2', 's2', 's2', 's3', 's3', 's3', 's3']df# 这是我尝试生成图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  labels1  0.433731  0.886622  0.683993  0.125918  0.398787      1s1  0.719834  0.435971  0.935742  0.885779  0.460693      1s2  0.324877  0.962413  0.366274  0.980935  0.487806      2s2  0.600318  0.633574  0.453003  0.291159  0.223662      2s3  0.741116  0.167992  0.513374  0.485132  0.550467      3s3  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  labels1  0.442293  0.470318  0.559764  0.829743  0.146971      1s1  0.603235  0.218269  0.516422  0.295342  0.466475      1s2  0.569428  0.109494  0.035729  0.548579  0.760698      2s2  0.600318  0.633574  0.453003  0.291159  0.223662      2s3  0.412750  0.079504  0.433272  0.136108  0.740311      3s3  0.462627  0.025328  0.245863  0.931857  0.576927      3

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注