【问题标题】:Pandas Sample Based on Two Criteria基于两个标准的 Pandas 样本
【发布时间】:2021-12-08 11:22:43
【问题描述】:

我有一个如下所示的数据框:

     feature     target
0       2        0
1       0        0
2       0        0
3       0        0
4       1        0
...    ...      ...
33208   1        0
33209   0        0
33210   2        0
33211   2        0
33212   1        0

feature 列中有 3 个类(0、1、2),target 列中有两个类(0、1)。如果我按这两列对数据框进行分组,我会得到:

df.groupby(['feature', 'target']).size()

feature  target
0         0             4282
          1               81
1         0             8537
          1               37
2         0            20161
          1              115
dtype: int64

每个feature 类都有0s1s 作为target 值,我需要找到一种对这些值进行采样的方法,我的意图是最后有这样的东西:

new_df.groupby(['feature', 'target']).size()

feature  target
0         0             4282
          1               81
1         0             4282
          1               37
2         0             4282
          1              115
dtype: int64

我需要对每个feature 类的target 值进行抽样,有什么建议吗?

【问题讨论】:

  • 这不是已经采样了吗?

标签: python pandas pandas-groupby


【解决方案1】:

您有不同的分布,具体取决于feature 的值。 您需要从分布中采样 n 值,前提是 feature 的值:假设有 2 种可能的结果,这是一个二项分布问题。
下面显示的方法应该有助于target 不一定是(0, 1) 的情况 - 可以是任何东西(win vs looseteam A vs B 队,等等)据我所知:

import numpy as np
import pandas as pd

# this is just reproducting your grouped end stated
df = pd.DataFrame({"feature":[0, 0, 1, 1, 2, 2], "target":[0, 1, 0, 1, 0, 1], "number":[4282, 81, 4282, 37, 4282, 115]})
df = df.set_index(["feature", "target"])

def sample_values(feature, sample_size):
    # select one of the distribution by feature
    df_sub = df.loc[feature]

    (event1, number1), (event2, number2) = zip(df_sub.index,df_sub["number"].tolist())

    return [event2 if np.random.binomial(1, number2/(number1+number2))==1 else event1 for _ in range(sample_size)]

print(sample_values(2, 100))

输出

[1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    相关资源
    最近更新 更多