Python - 每组 Pandas 随机抽样

标签 python pandas numpy random

我有一个与它非常相似的数据框,但有数千个值:

import numpy as np
import pandas as pd 

# Setup fake data.
np.random.seed([3, 1415])      
df = pd.DataFrame({
    'Class': list('AAAAAAAAAABBBBBBBBBB'),
    'type': (['short']*5 + ['long']*5) *2,
    'image name': (['image01']*2  + ['image02']*2)*5,
    'Value2': np.random.random(20)})

我能够找到一种方法,使用以下代码对每个图像、每个类别和每个类型的 2 个值进行随机抽样:

df2 = df.groupby(['type', 'Class', 'image name'])[['Value2']].apply(lambda s: s.sample(min(len(s),2)))

我得到了以下结果:

My table

我正在寻找一种对该表进行子集化的方法,以便能够根据类型和类别随机选择随机图像(“图像名称”)(并为随机选择的图像保留 2 个值。

我想要的输出的 Excel 示例:

Desired output

最佳答案

IIUC,问题是您不想对 image name 列进行分组,但如果该列未包含在分组依据中,您将丢失该列

你可以先创建grouby对象

gb = df.groupby(['type', 'Class'])

现在您可以使用列表推导来交互 grouby block

blocks = [data.sample(n=1) for _,data in gb]

现在您可以连接 block ,以重建随机采样的数据帧

pd.concat(blocks)

输出

   Class    Value2 image name   type
7      A  0.817744    image02   long
17     B  0.199844    image01   long
4      A  0.462691    image01  short
11     B  0.831104    image02  short

您可以修改您的代码并将列 image name 添加到 groupby 中,就像这样

df.groupby(['type', 'Class'])[['Value2','image name']].apply(lambda s: s.sample(min(len(s),2)))

                  Value2 image name
type  Class
long  A     8   0.777962    image01
            9   0.757983    image01
      B     19  0.100702    image02
            15  0.117642    image02
short A     3   0.465239    image02
            2   0.460148    image02
      B     10  0.934829    image02
            11  0.831104    image02

编辑:保持每组图像相同

我不确定您是否可以避免对这个问题使用迭代过程。您可以只遍历 groupby block ,过滤组,获取随机图像并保持每个组的名称相同,然后像这样从剩余图像中随机抽样

import random

gb = df.groupby(['Class','type'])
ls = []

for index,frame in gb:
    ls.append(frame[frame['image name'] == random.choice(frame['image name'].unique())].sample(n=2))

pd.concat(ls)

输出

   Class    Value2 image name   type
6      A  0.850445    image02   long
7      A  0.817744    image02   long
4      A  0.462691    image01  short
0      A  0.444939    image01  short
19     B  0.100702    image02   long
15     B  0.117642    image02   long
10     B  0.934829    image02  short
14     B  0.721535    image02  short

关于Python - 每组 Pandas 随机抽样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49619681/

相关文章:

python - 在 Python MySQL 中执行 INSERT 查询的正确方法是什么?

python - Pandas 数据框 fillna() 不工作?

python - 如何绘制梯度(f(x,y))?

python - 如何防止Pandas出现 "None of [MultiIndex...] are in the [columns]"?

python - 'ndarray' 类型的对象不是 JSON 可序列化的

python - 在 Python 中循环用户定义的日期

python - pyqt中的数据库 View

python - 为什么 select 查询在 Python 中不执行,而在 MYSQL 中它有返回值?

python - 通过匹配 Pandas DataFrame 中另一列中的值来获得行值的差异

python - Pandas :聚合具有多种功能的多列