2014-01-27 46 views
1

所以现在,如果我多个列表,即x = [1,2,3]* 2 I get x as [1,2,3,1,2,3]但是这不适用于大熊猫。复制熊猫DF N次

所以,如果我想复制大熊猫DF我必须做出一个列的列表和多种:

col_x_duplicates = list(df['col_x'])*N 

new_df = DataFrame(col_x_duplicates, columns=['col_x']) 

然后做对原始数据的加入:

pd.merge(new_df, df, on='col_x', how='left') 

这就是现在复制大熊猫N次,有没有更简单的方法?甚至更快的方法?

+1

numpy的的重复()可能是有用的(和快速)在这里。请参阅http://stackoverflow.com/questions/1550130/cloning-row-or-column-vectors。 – capitalistcuttle

+0

你想让输出栏看起来像是[1,2,3,1,2,3]还是'[1,1,2,2,3,3]'? – DSM

回答

1

其实,既然你要复制的数据框整体(而不是每个元素),numpy.tile()可能会更好:

In [69]: import pandas as pd 

In [70]: arr = pd.np.array([[1, 2, 3], [4, 5, 6]]) 

In [71]: arr 
Out[71]: 
array([[1, 2, 3], 
     [4, 5, 6]]) 

In [72]: df = pd.DataFrame(pd.np.tile(arr, (5, 1))) 

In [73]: df 
Out[73]: 
    0 1 2 
0 1 2 3 
1 4 5 6 
2 1 2 3 
3 4 5 6 
4 1 2 3 
5 4 5 6 
6 1 2 3 
7 4 5 6 
8 1 2 3 
9 4 5 6 

[10 rows x 3 columns] 

In [75]: df = pd.DataFrame(pd.np.tile(arr, (1, 3))) 

In [76]: df 
Out[76]: 
    0 1 2 3 4 5 6 7 8 
0 1 2 3 1 2 3 1 2 3 
1 4 5 6 4 5 6 4 5 6 

[2 rows x 9 columns] 
+0

非常感谢!在大熊猫df上运行它时,耻辱似乎很慢! – redrubia

+0

你知道如果快捷方式? – redrubia

+0

@redrubia你是否多次调用tile()?它可能会很慢,因为您每次都分配额外的内存。如果你知道最终的大小(毕竟重复),你可以尝试初始化一个零大小的数组,然后用切片填充它。 – capitalistcuttle