【问题标题】:How to randomly select rows from Pandas dataframe based on a specific condition?如何根据特定条件从 Pandas 数据框中随机选择行?
【发布时间】:2019-06-07 10:06:51
【问题描述】:

假设我有一个 Pandas 数据框 df,它具有以下结构:-

         Column 1      Column 2 ....     Column 100
Row 1    0.233           0.555              0
Row 2    0.231           0.514              2
..
Row 15000    0.232           0.455          3

Column 100 表示每行所属的特定类(可以来自0-14)。每个类别/类都有与之关联的1000 行。对于每个类别(用Column 100 中的整数表示),我只想随机选择200 样本,并创建一个新的数据框df_new,其新维度为15x200 = 3000 rows。有什么好办法吗?

【问题讨论】:

  • df.groupby('Column 100').apply(lambda x:x.sample(200)) ??

标签: python pandas dataframe random


【解决方案1】:

每组使用DataFrame.sample - 然后对最后一列进行排序:

np.random.seed(2019)
df = (pd.DataFrame(np.random.randint(15, size=(100000, 100)))
         .rename(columns=lambda x: f'Column {x+1}'))
#print (df.head())


N = 200
df1 = df.groupby('Column 100').apply(lambda x:x.sample(N)).reset_index(drop=True)
#print (df1.head())

print (len(df1))
3000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 2013-04-02
    相关资源
    最近更新 更多