python - 如何从 DataFrame 中的每个组中采样不同数量的行

标签 python python-3.x dataframe random pandas-groupby

我有一个带有类别列的数据框。 Df 每个类别的行数不同。

category number_of_rows
cat1     19189
cat2     13193
cat3     4500
cat4     1914
cat5     568
cat6     473
cat7     216
cat8     206
cat9     197
cat10    147
cat11    130
cat12    49
cat13    38
cat14    35
cat15    35
cat16    30
cat17    29
cat18    9
cat19    4
cat20    4
cat21    1
cat22    1
cat23    1

我想从每个类别中选择不同的行数。 (而不是每个类别的 n 固定行数)

Example input:
size_1 : {"cat1": 40, "cat2": 20, "cat3": 15, "cat4": 11, ...}
Example input: 
size_2 : {"cat1": 51, "cat2": 42, "cat3": 18, "cat4": 21, ...}

我想做的实际上是分层抽样,每个类别对应给定数量的实例。

此外,它应该是随机选择的。例如,我不需要 size_1.["cat1"] 的前 40 个值,我需要随机 40 个值。

感谢您的帮助。

最佳答案

人工数据生成

<小时/>

数据框

让我们首先生成一些数据来看看如何解决问题:

# Define a DataFrame containing employee data 
df = pd.DataFrame({'Category':['Jai', 'Jai', 'Jai', 'Princi', 'Princi'], 
        'Age':[27, 24, 22, 32, 15], 
        'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 
        'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th']} )

抽样规则

# Number of rows, that we want to be sampled from each category 
samples_per_group_dict = {'Jai': 1, 
                          'Princi':2}


解决问题

<小时/>

我可以提出两种解决方案:

  1. 应用于 groupby(单行)

    output = df.groupby('Category').apply(lambda group: group.sample(samples_per_group_dict[group.name])).reset_index(drop = True)
    
  2. 循环组(更详细)

    list_of_sampled_groups = []
    
    for name, group in df.groupby('Category'):    
        n_rows_to_sample = samples_per_group_dict[name]
        sampled_group = group.sample(n_rows_to_sample)
        list_of_sampled_groups.append(sampled_group)
    
    output = pd.concat(list_of_sampled_groups).reset_index(drop=True)
    

两种方法的性能应该相同。如果性能很重要,您可以对计算进行矢量化。但具体的优化取决于每组中的 n_groups 和 n_samples。

关于python - 如何从 DataFrame 中的每个组中采样不同数量的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59437334/

相关文章:

python - 在 pandas DataFrame 中存储 3 维数据

python - 从 Jupyter 使用 Python 设置 Drive API 时出错

python - openpyxl 行迭代器忽略 row_offset 参数?

python - Python 中的 *tuple 和 **dict 是什么意思?

python - 类型错误 : descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'int' object

python - Pandas - 将应用函数的结果数据帧合并到新的数据帧中

python - Django 表单的 HTTP 响应问题

python - 根据 pandas 索引范围合并行

python - 将一行分布在共享相同键的其他行上

python - 识别多个数据框中的重叠行