【问题标题】:A more efficient way of aggregating a random sample from pandas dataframe and iteratively append the mean of sampled df in an empty dataframe一种从 pandas 数据帧中聚合随机样本并迭代地将采样 df 的平均值附加到空数据帧中的更有效方法
【发布时间】:2020-01-16 15:51:18
【问题描述】:

我正在尝试从我的 df 中取出一个随机样本,使用 df_sample.mean(axis =0) 对单行系列中的所有列取平均值,然后将此系列附加到一个空数据框,我想要 100 万这样的行。我得到了结果,但是运行时间太长了。有人可以建议一种有效的方法吗?

train = pd.DataFrame()

for i in range (1000000):

    df_sample  = df_2.sample(n=100)
    row = df_sample.mean(axis=0)
    train = train.append(row,ignore_index=True)

【问题讨论】:

  • 我很困惑。您从数据框中采样 100 条记录,计算每行的平均值,从而为您提供 100 维列向量,然后将其作为一行附加到新数据框中?这样做的目的是什么?
  • 获取具有连续变量的聚合数据集(因为均值)。我的原始数据集只有分类变量。所以,这就是为什么

标签: pandas dataframe for-loop aggregate sampling


【解决方案1】:

这是一种更快的方法,这将产生 100 万(100 万)行:

方法一:使用内置 pandas 进行采样

n_times = 1000000
values = [df_2.sample(n=1).mean(axis=0, numeric_only=True) for _ in range (n_times)]
train = pd.DataFrame(values, columns=['mean_col'])

方法2:使用numpy进行采样

def f1():
    return np.mean(df_2.values[np.random.randint(0, df.shape[0])])

def f2():
    return df_2.iloc[np.random.randint(0, df.shape[0])].mean(axis=0, numeric_only=True)

values = [f1() for _ in range(n_times)]
train = pd.DataFrame(values, columns=['mean_col'])

values = [f2() for _ in range(n_times)]
train = pd.DataFrame(values, columns=['mean_col'])

【讨论】:

  • 不是更快的方式,花费几乎相同的时间
猜你喜欢
  • 2017-06-01
  • 2019-06-05
  • 2021-10-06
  • 1970-01-01
  • 2016-10-31
  • 2018-04-17
  • 1970-01-01
  • 2015-12-21
  • 2018-02-01
相关资源
最近更新 更多