How to duplicate Python dataframe one by one?

后端 未结 5 1702
面向向阳花
面向向阳花 2021-01-05 13:01

I have a pandas.DataFrame as follows:

df1 = 
    a    b
0   1    2
1   3    4

I\'d like to make this three times to become:

5条回答
  •  甜味超标
    2021-01-05 13:25

    Build a one dimensional indexer to slice both the the values array and index. You must take care of the index as well to get your desired results.

    • use np.repeat on an np.arange to get the indexer
    • construct a new dataframe using this indexer on both values and the index

    r = np.arange(len(df)).repeat(3)
    pd.DataFrame(df.values[r], df.index[r], df.columns)
    
       a  b
    0  1  2
    0  1  2
    0  1  2
    1  3  4
    1  3  4
    1  3  4
    

提交回复
热议问题