基于列

时间:2019-05-17 18:00:09

标签: pandas dataframe

我有一个大的数据框,我想根据target列值(二进制值:0/1)上的值进行采样

我想提取“目标”列中具有0和1的相等数量的行。我当时在考虑使用pandas采样函数,但不确定如何基于target列从两个类中为数据帧声明相等数量的样本。

我正在考虑使用类似这样的东西:

df.sample(n=10000, weights='target', random_state=1)

不确定如何编辑它,以在1's列中使用5k 0's和5k target获取10k记录。任何帮助表示赞赏!

4 个答案:

答案 0 :(得分:3)

您可以使用 DataFrameGroupBy.sample 方法如下:

sample_df = df.groupby("target").sample(n=5000, random_state=1)

答案 1 :(得分:1)

您可以按目标对数据进行分组,然后进行采样

df = pd.DataFrame({'col':np.random.randn(12000), 'target':np.random.randint(low = 0, high = 2, size=12000)})
new_df = df.groupby('target').apply(lambda x: x.sample(n=5000)).reset_index(drop = True)

new_df.target.value_counts()

1    5000
0    5000

答案 2 :(得分:0)

您将必须运行df0.sample(n = 5000)和df1.sample(n = 5000),然后将df0和df1合并到dfsample数据帧中。您可以使用某些逻辑通过df.filter()创建df0和df1。如果您提供示例数据,我可以帮助您构建该逻辑。

答案 3 :(得分:0)

也发现这是一个好方法:

df['weights'] = np.where(df['target'] == 1, .5, .5)
sample_df = df.sample(frac=.1, random_state=111, weights='weights')

根据要从原始数据框中返回的数据百分比,更改frac的值。

相关问题