【问题标题】:Pandas: select rows by random groups while keeping all of the group's variablesPandas:按随机组选择行,同时保留所有组的变量
【发布时间】:2022-01-10 12:25:47
【问题描述】:

我的数据框如下所示:

id  std     number 
A   1       1
A   0       12
B   123.45  34
B   1       56 
B   12      78
C   134     90
C   1234    100
C   12345   111

我想选择 Id 的随机行,同时保留其他行中的所有信息,这样数据框将如下所示:

id  std     number 
A   1       1
A   0       12
C   134     90
C   1234    100
C   12345   111

我试过了

size = 1000   
replace = True  
fn = lambda obj: obj.loc[np.random.choice(obj.index, size, replace),:]
df2 = df1.groupby('Id', as_index=False).apply(fn)

df2 = df1.sample(n=1000).groupby('id')

但显然这不起作用。任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas random pandas-groupby rows


    【解决方案1】:

    您需要先创建随机ids,然后在boolean indexing 中通过Series.isin 比较原始列id

    #number of groups
    N = 2
    df2 = df1[df1['id'].isin(df1['id'].drop_duplicates().sample(N))]
    print (df2)
      id      std  number
    0  A      1.0       1
    1  A      0.0      12
    5  C    134.0      90
    6  C   1234.0     100
    7  C  12345.0     111
    

    或者:

    N = 2
    df2 = df1[df1['id'].isin(np.random.choice(df1['id'].unique(), N))]
    

    【讨论】:

      猜你喜欢
      • 2013-06-14
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多