如何重复Pandas数据框?

lsh*_*eng 39 python duplicates repeat dataframe pandas

这是我应该重复5次的数据框:

>>> x = pd.DataFrame({'a':1,'b':2},index = range(1))
>>> x
   a  b
0  1  2
Run Code Online (Sandbox Code Playgroud)

我想得到这样的结果:

>>> x.append(x).append(x).append(x)
   a  b
0  1  2
0  1  2
0  1  2
0  1  2
Run Code Online (Sandbox Code Playgroud)

但是必须有一种比继续追加更聪明的方法..实际上我正在研究的数据框应该重复50次.

我还没有找到任何实用的东西,包括那些像np.repeat----它只是在数据框架上工作.

有人可以帮忙吗?

jor*_*ris 57

你可以使用这个concat功能:

In [13]: pd.concat([x]*5)
Out[13]: 
   a  b
0  1  2
0  1  2
0  1  2
0  1  2
0  1  2
Run Code Online (Sandbox Code Playgroud)

如果您只想重复值而不是索引,则可以执行以下操作:

In [14]: pd.concat([x]*5, ignore_index=True)
Out[14]: 
   a  b
0  1  2
1  1  2
2  1  2
3  1  2
4  1  2
Run Code Online (Sandbox Code Playgroud)


And*_*den 18

我认为现在使用它更干净/更快iloc:

In [11]: np.full(3, 0)
Out[11]: array([0, 0, 0])

In [12]: x.iloc[np.full(3, 0)]
Out[12]:
   a  b
0  1  2
0  1  2
0  1  2
Run Code Online (Sandbox Code Playgroud)

更一般地说,您可以使用tilerepeat使用arange:

In [21]: df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])

In [22]: df
Out[22]:
   A  B
0  1  2
1  3  4

In [23]: np.tile(np.arange(len(df)), 3)
Out[23]: array([0, 1, 0, 1, 0, 1])

In [24]: np.repeat(np.arange(len(df)), 3)
Out[24]: array([0, 0, 0, 1, 1, 1])

In [25]: df.iloc[np.tile(np.arange(len(df)), 3)]
Out[25]:
   A  B
0  1  2
1  3  4
0  1  2
1  3  4
0  1  2
1  3  4

In [26]: df.iloc[np.repeat(np.arange(len(df)), 3)]
Out[26]:
   A  B
0  1  2
0  1  2
0  1  2
1  3  4
1  3  4
1  3  4
Run Code Online (Sandbox Code Playgroud)

注意:这适用于非整数索引的DataFrame(和Series).


U10*_*ard 5

尝试使用numpy.repeat

>>> df=pd.DataFrame(pd.np.repeat(x.values,5,axis=0),columns=x.columns)
>>> df
   a  b
0  1  2
1  1  2
2  1  2
3  1  2
4  1  2
>>> 
Run Code Online (Sandbox Code Playgroud)