如何使用原始 DF 中的索引创建新的 DataFrame 重复行

How to create a new DataFrame repeating rows using indexes from original DF

我有一个生成随机代理的 DataFrame。但是,我想扩展它们以匹配我正在寻找的人口,所以我需要根据我的抽样索引重复行。

这是一个永远持续的循环代码:

df = pd.DataFrame({'a': [0, 1, 2]})    
sampled_indexes = [0, 0, 1, 1, 2, 2, 2]
new_df = pd.DataFrame(columns=['a'])
for i, idx in enumerate(sampled_indexes):
    new_df.loc[i] = df.loc[idx]

那么,原始DataFrame:

df
   a
0  0
1  1
2  2

给我一个放大的新数据框的结果

new_df
   a
0  0
1  0
2  1
3  1
4  2
5  2
6  2

因此,对于具有 34,000 行或更多行(永远需要)的 DataFrame,此循环太慢了。

我怎样才能更简单、更快地做到这一点?

你可以做到 DataFrame.merge:

df = pd.DataFrame({'a': [0, 1, 2]})
sampled_indexes = [0, 0, 1, 1, 2, 2, 2]

print( df.merge(pd.DataFrame({'a': sampled_indexes})) )

打印:

   a
0  0
1  0
2  1
3  1
4  2
5  2
6  2

使用 sampled_indexes 重新索引数据帧,然后重置索引。

df.reindex(sampled_indexes).reset_index(drop=True)