Python pandas样本没有混合索引



我想对数据帧的索引的每个值独立地应用Pandas的sample函数。这可以用for循环来完成,如下所示:

import pandas
df = pandas.DataFrame({'something': [3,4,2,2,6,7], 'n': [1,1,2,2,3,3]})
df.set_index(['n'], inplace=True)
resampled_as_I_want_df = df[0:0]
for i in sorted(set(df.index)):
resampled_as_I_want_df = resampled_as_I_want_df.append(
df.loc[i].sample(frac=1, replace=True),
)
print(resampled_as_I_want_df)

让我用一种人性化的方式来解释这一点。df数据帧如下所示:

something
n           
1          3
1          4
2          2
2          2
3          6
3          7

现在我们看到有三个";索引组";其具有值123。我想做的是应用sample函数,使新的数据帧具有相同的索引,而不进行随机采样,并且在每个组中执行采样,就好像它们是独立的数据帧一样。

有没有办法避免for循环?对于大型数据帧来说,这是一个瓶颈。

使用df.groupby(level=0).sample(frac=1, replace=True)

最新更新