How to duplicate Python dataframe one by one?

后端 未结 5 1558
面向向阳花
面向向阳花 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:12

    You can use numpy.repeat with parameter scalar 3 and then add columns parameter to DataFrame constructor:

    df = pd.DataFrame(np.repeat(df.values, 3, axis=0), columns=df.columns)
    print (df)
       a  b
    0  1  2
    1  1  2
    2  1  2
    3  3  4
    4  3  4
    5  3  4
    

    If really want duplicated index what can complicated some pandas functions like reindex which failed:

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

提交回复
热议问题